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 original 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 for
loop.
Wiki Markup |
---|
As detailed in the JLS, [§14.14.2, "The Enhanced For Statement" |http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\]: |
an An enhanced
for
statement of the form
Code Block for (ObjType obj : someIterableItem) { // ... }is equivalent to a standard basic
for
loop of the form
Code Block for (Iterator myIterator = someIterableItem.iterator(); myIterator.hasNext();) { ObjType obj = myIterator.next(); // ... }
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 it can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for
statement.
...
The attempt to skip to the next item appears to succeed because the assignment is successful and the value of processMe
is updated. Unlike an original a basic for
loop, however, the assignment leaves the overall iteration order of the loop unchanged. As a resultConsequently, the object following the skipped object is processed twice.
...
This compliant solution correctly processes the objects each object in the collection no more than one timeonce.
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 } |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="60b962dbad59c2c5-0081b8f2-4e7f42be-b7bca6e8-7eb1dd9c856ef962e2a11281"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§14.14.2,"The enhanced for statement"The Enhanced For Statement | http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] | ]]></ac:plain-text-body></ac:structured-macro> |
...