There are 3 preferable ways to traverse through a collection and lets see what all are they and when to use them
- If you have an iterable and need to traverse unconditionally to all of them, i.e in case where we do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the
Collection
in any wayfor (iterable_type iterable_element : collection)
- If you have an iterable but need to conditionally traverse:
for (Iterator iterator = collection.iterator(); iterator.hasNext();)
- If data-structure does not implement iterable:
for (int i = 0; i < collection.length; i++)
EXAMPLE
public static void traverse(List data) {
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());
}
}
No comments:
Post a Comment