List object reference changed during Java loop

iterator, java, loops

Solution

No, the iteration won't be reset. According to the JLS:

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

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

The definition makes it obvious that the iterator is only initialised once, before the first iteration of the loop.

The behaviour when iterating across an array with an enhanced for statement is similar in this respect.

However I'd personally consider it poor practice as it makes the code hard to understand.

Problem

I couldn't find any topic about this. I want to know if it is safe to change the reference for the list class during a loop like the one bellow: ``` Tree minimalTree = someTree; for (Tree st : minimalTree.getSubtrees()) { if (condition) minimalTree = st; } ``` Does the iterator gets reset and starts again for the new reference? Edit: I forgot to say: this code is suited for situations where I want to narrow down the search for elements in the tree, let's say, the smaller tree that contains certain elements. In this case, it would be faster to keep looking only for the inner structures of "minimalTree" instead of the entire "someTree" structure.

Original source