Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

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.

Wiki MarkupAs 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]\]:

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] ]

[§14.14.2,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>

...

      01. Declarations and Initialization (DCL)      02. Expressions (EXP)