Using an iterator from a List is like using any other iterator.
The order of the elements in the list is preserved.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class MainClass {
public static void main(String[] a) {
List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
Iterator iter = list.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
运行结果如下:
Looping through a Collection object: while loop, iterator, and for each
import java.util.ArrayList;
import java.util.Iterator;
// w w w. j av a 2s.c o m
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Monday");
list.add("Tuesdag");
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Sunday");
Iterator<String> iterator = null;
iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
for (iterator = list.iterator(); iterator.hasNext();) {
String element = iterator.next();
System.out.println(element);
}
for (String element : list) {
System.out.println(element);
}
}
}
运行结果如下: