Programming Tutorials

(追記) (追記ここまで)

Iterate a List in Java

By: Dorris in Java Tutorials on 2010年12月27日 [フレーム]

This tutorial demonstrates the use of ArrayList, Iterator and a List. There are many ways to iterate a list of objects in Java. This sample program shows you the different ways of iterating through a list in Java.

In java a list object can be iterated in following ways:

  • Using Iterator class
  • With the help of for loop
  • With the help of while loop
  • Java 5 for-each loop

Following example code shows how to iterate a list object:

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class IterateAList {
 public static void main(String[] args) {
 List arrJavaTechnologies = new ArrayList();
 arrJavaTechnologies.add("JSP");
 arrJavaTechnologies.add("Servlets");
 arrJavaTechnologies.add("EJB");
 arrJavaTechnologies.add("JDBC");
 arrJavaTechnologies.add("JPA");
 arrJavaTechnologies.add("JSF");
 // Iterate with the help of Iterator class
 System.out.println("Iterating with the help of Iterator class");
 Iterator iterator = arrJavaTechnologies.iterator();
 while (iterator.hasNext()) {
 System.out.println(iterator.next());
 }
 // Iterate with the help of for loop
 System.out.println("Iterating with the help of for loop");
 for (int i = 0; i < arrJavaTechnologies.size(); i++) { System.out.println(arrJavaTechnologies.get(i)); } // Iterate with the help of while loop System.out.println("Iterating with the help of while loop"); int j = 0; while (j < arrJavaTechnologies.size()) { System.out.println(arrJavaTechnologies.get(j)); j++; } // Iterate with the help of Java 5 for-each loop System.out.println("Iterate with the help of Java 5 for-each loop"); for (String element : arrJavaTechnologies) { System.out.println(element); } } } 



(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /