List of link objects changed during Java cycle

I could not find a single topic about this. I want to know if it is possible to change the link for a list class during a loop, as shown below:

Tree minimalTree = someTree; for (Tree st : minimalTree.getSubtrees()) { if (condition) minimalTree = st; } 

An iterator gets reset and starts again for a new link?

Edit: I forgot to say: this code is suitable for situations where I want to narrow my search for elements in a tree, say a smaller tree containing certain elements. In this case, it would be faster to search only the internal structures of "minimalTree" instead of the entire structure of "someTree".

+7
java iterator loops
source share
2 answers

No, the iteration will not reset. According to JLS :

The extension for approval is equivalent to the basic form for approval:

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

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

The behavior when iterating over an array with an extension for an operator is similar in this respect.

However, I personally consider this a bad practice, as this makes it difficult to understand the code.

+6
source share

Actually, there are two questions:

I want to know if it is possible to change the link for a list class during a loop, as shown below:

Yes, it is safe. And for security, I mean: changing the link does not interfere with an already running cycle.

An iterator gets reset and starts again for a new link?

No, the iterator will never reset. That would be exactly the opposite of safe.

In my opinion, it is not a good practice to change iterator or collection variables inside a loop. This makes it difficult to understand the code, and probably the result is not what you expect when you do it (for example, in your case, I realized that you expected the loop to begin re-evaluating the collection).

In your case, encapsulate the method and call it recursively in the subtree:

 Tree findMinimalTree(Tree tree) { for (Tree st : tree.getSubtrees()) { if (condition) return findMinimalTree(st); } return tree; } 
+2
source share

All Articles