On the semantics of enhanced for loop
Here is the relevant excerpts from the Java Language Specification 3rd Edition, slightly edited for clarity:
The enhanced for statement has the form:
for ( Type Identifier : Expression ) Statement
If the type of Expression is an array type, T[], then the meaning of the enhanced for statement is given by the following basic for statement:
T[] a = Expression;
for (int i = 0; i < a.length; i++) {
Type Identifier = a[i];
Statement
}
where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
So in fact the language does guarantee that Expression will only be evaluated once.
For completeness, here's the equivalence when the Expression is of type Iterable:
The enhanced for statement has the form:
for ( Type Identifier : Expression ) Statement
If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:
for (I iter = Expression.iterator(); iter.hasNext(); ) {
Typ
answered 2010-08-08T09:25:22.800