Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: updated JLS quote

...

The JLS provides the following example of the enhanced for statement in §14.14.2, "The Enhanced for Statement" [JLS 2014]:

Wiki Markup
The enhanced for statement is equivalent to a basic for statement of the form:

for (I

For example, this code:

Code Block
List<? extends Integer> l = ...
for (float i : l) ...

will be translated to:

Code Block
for (Iterator<Integer> #i = lExpression.iterator(); #i.hasNext(); ) {
float #i0    {VariableModifier} TargetType Identifier =
  (Integer)      (TargetType) #i.next();
...
 
    Statement
}
    
#i is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope...at the point where the enhanced for statement occurs.

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, 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 can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.

...