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
forstatement of the form
Code Block for (ObjType obj : someIterableItem) { // ... }is equivalent to a basic
forloop 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="838ac619-5f57-47b4-a446-681251a62c02"><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)