Prior to release 1.5
// No longer the preferred idiom to iterate over a collection!
for (Iterator i = c.iterator(); i.hasNext(); ) {
doSomething((Element) i.next()); // (No generics before 1.5)
}
// No longer the preferred idiom to iterate over an array!
for (int i = 0; i < a.length; i++) {
doSomething(a[i]);
}
The for-each loop, introduced in release 1.5
// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
doSomething(e);
}
Advantages over traditional for-loop
Three common situations where you can’t use a for-each loop
- Filtering
If you need to traverse a collection and remove selected elements, then you need to use an explicit iterator so that you can call its remove method.
- Transforming
If you need to traverse a list or array and replace some or all of the values of its elements, then you need the list iterator or array index in order to set the value of an element.
- Parallel iteration
If you need to traverse multiple collections in parallel, then you need explicit control over the iterator or index variable, so that all it- erators or index variables can be advanced in lockstep (as demonstrated unin- tentionally in the buggy card and dice examples above).