java.util.List
:- Using a traditional
for
loop; - Using a simplified
for
loop, or "foreach" statement in JDK 5 ; - Using
java.util.Iterator
public static void traverse(List data) {I always use the
System.out.println("Using simplified for loop/foreach:");
for(Object obj : data) {
System.out.println(obj);
}
System.out.println("Using for loop:");
for(int i = 0, n = data.size(); i < n; i++) {
System.out.println(data.get(i));
}
System.out.println("Using Iterator:");
for(Iterator it = data.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
for
loop and JDK 5 enhanced for loop, and avoid using Iterator
to traverse List
. If you see other ways, feel free to add them in comment section.PS:
Is there a foreach statement in JDK 1.5? Yes, but the word foreach is not a keyword in java, and I doubt it will ever be. Java foreach statement uses a simplified, or enhanced for loop (see examples above). Therefore, JDK 1.5 doesn't need to introduce new keywords like foreach, forEach, or for each, and foreach/forEach can continue to be used as valid identifier/variable names.