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.
As detailed in the JLS, [§14§14.14.2, "The Enhanced For Statement" |http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] \[ [JLS 2005|AA. References#JLS 05]\]: Wiki Markup
An enhanced
for
statement of the form
Code Block for (ObjType obj : someIterableItem) { // ... }is equivalent to a basic
for
loop of the form
Code Block for (Iterator myIterator = someIterableItem.iterator(); myIterator.hasNext();) { ObjType obj = myIterator.next(); // ... }
...
This rule is easily enforced with static analysis.
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ecba307d-cfdd-4e71-91d0-1433208841ec"><ac:plain-text-body><! [CDATA[ [[JLS 2005AA. References#JLS 05] ] | http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] | ]]></ac:plain-text-body></ac:structured-macro> |
...
01. Declarations and Initialization (DCL) 02. Expressions (EXP)