Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The enhanced for statement introduced in Java 1.5 (a.k.a. the for-each idiom) is primarily used for iterating over collections of objects. Unlike the original for statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. Thus, assignments to the loop variable may can have an effect other than that 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 Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 14.14.2, "The enhanced for statement", 

an

...

enhanced

...

for

...

statement

...

of

...

the

...

form

Code Block

for (ObjType obj : someIterableItem) { 
  // ...
}

is equivalent to a standard for loop of the form

Code Block

for (Iterator myIterator = someIterableItem.iterator(); iterator.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 may it can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.

...

Assignments to the loop variable of an enhanced for loop (for-each idiom) fail to affect the overall iteration order, lead to programmer confusion, and may can leave data in a fragile or inconsistent state.

...