My preference is
1) If I need to move forward through the list without any modification to the List object, for readable and clean code, I will use:
for(MyClass mc : list){
/* code without modification to list */
}
2) If I need modification to the List object, no doubt I will use:
iter = list.iterator();
while(iter.hasNext()) {
MyClass mc = iter.next()
/* code without modification to list */
/* code with modification to list */
}
Additional Information:
Iterator will be useful if you need to create a utility method that can traverse multiple type of collection (e.g. ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet)
public class Example {
public static void iterateAndDoSomething(Iterator<MyClass> iter) {
while(iter.hasNext()) {
MyClass mc = iter.next();
/* code without modification to list */
/* code with modification to list */
}
}
public static void main(String[] args) {
ArrayList<MyClass> als = new ArrayList<MyClass>();
TreeSet<MyClass> tss = new TreeSet<MyClass>();
iterateAndDoSomething(als.iterator());
iterateAndDoSomething(tss.iterator());
}
}