The enhanced for
statement introduced in Java 5 (also known as the for-each idiom) is primarily used for iterating over collections of objects. Unlike the basic for
statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. Consequently, assignments to the loop variable can have an effect other than what is intended by the developer. This provides yet another reason to avoid assigning to the loop variable in a enhanced for
loop.designed for iteration through Collections and arrays .
The JLS provides the following example of the enhanced for
statement in As detailed in the JLS, §14.14.2, "The Enhanced For for
Statement" [JLS 20052014]:
An enhanced
for
statement of the formFor example, this code:
Code Block List<? extends Integer> l = ... for (ObjTypefloat obji : someIterableItem) { //l) ... }is equivalent to a basic
for
loop of the formwill be translated to:
Code Block for (IteratorIterator<Integer> myIterator#i = someIterableIteml.iterator(); myIterator#i.hasNext(); ) { float ObjType obj#i0 = myIterator(Integer)#i.next(); // ... }
Unlike the basic for
statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. Consequently, an assignment to the loop variable is equivalent to modifying a variable local to the loop body whose initial value is the object referenced by the loop iterator. This modification is not necessarily erroneous, but can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for
statement.
...
This noncompliant code example attempts to process a collection of objects using an enhanced for
loop. It further intends to skip processing one item in the collection.
Code Block | ||
---|---|---|
| ||
Collection<ProcessObj> processThese = // ...
for (ProcessObj processMe: processThese) {
if (someCondition) { // found the item to skip
someCondition = false;
processMe = processMe.getNext(); // attempt to skip to next item
}
processMe.doTheProcessing(); // process the object
}
|
...
This compliant solution correctly processes each object in the collection no more than once.
Code Block | ||
---|---|---|
| ||
Collection<ProcessObj> processThese = // ...
for (final ProcessObj processMe: processThese) {
if (someCondition) { // found the item to skip
someCondition = false;
continue; // skip by continuing to next iteration
}
processMe.doTheProcessing(); // process the object
}
|
...
01. Declarations and Initialization (DCL) 02. Expressions (EXP)