Is foreach loop literally rewritten to a for loop with iterator?

compilation, foreach, java, syntactic-sugar

Solution

According to Oracle documentation on this, there is indeed code being generated, but it differs according to the type of the used obejct.

If you are using an array, the foreach loop will be translated as a for loop with index:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    VariableModifiersopt TargetType Identifier = #a[#i];
    Statement
    }

If you have an Iterable object, you get a loop with iterator like this:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier = (TargetType) #i.next();
    Statement
}

Problem

This post explains that foreach loop directly corresponds to using iterator. If I write a foreach loop is it literally going to be transformed into for with iterator? In particular, given loop: ``` for(Integer i : createList()){ System.out.println(i); } ``` Am I guaranteed to always call `createList()` only once no matter what? Is it rewritten as: ``` for(Iterator<Integer> i = createList().iterator(); i.hasNext(); ) { System.out.println(i.next()); } ``` in some kind of intermediate step or just happens to produce the same bytecode as the above?

Original source

Related problems