need clarification to Oracle tutorial explanation of when to use iterator vs for-each construct

Eliyahu Machluf :

At Oracle tutorial about collections https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html I see the following:

Use Iterator instead of the for-each construct when you need to:

1. Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
2. Iterate over multiple collections in parallel.

I understand the first option 'remove current element' which is supported by iterator and not supported by for-each construct. I need clarification about the second option 'iterate over multiple collections in parallel' which can be done with iterator and not by for-each. can someone supply an example of such scenario? As far as I understand the for-each can also be nested, so one can travel on several collections in parallel.

This is not duplicate of Iterator vs For-Each and of Iterator vs for as they ask about general comparison of iterator and for-each, and I ask about the specific sentence at oracle tutorial.

T.J. Crowder :

Suppose you have two collections:

List<A> listA = /*...*/;
List<B> listB = /*...*/;

...and you need to iterate through them in parallel (that is, process the first entry in each, then process the next entry in each, etc.) You can't do that with the enhanced for loop, you'd use Iterators:

Iterator<A> itA = listA.iterator();
Iterator<B> itB = listB.iterator();
while (itA.hasNext() && itB.hasNext()) {
    A nextA = itA.next();
    B nextB = itB.next();
    // ...do something with them...
}

To be fair, you could combine an enhanced for loop with an iterator:

Iterator<A> itA = listA.iterator();
for (B nextB : listB) {
    if (!itA.hasNext()) {
        break;
    }
    A nextA = itA.next();
    // ...do something with them...
}

...but it's clumsy and clarity suffers, only one of the collections can be the subject of the for, the rest have to be Iterators.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85421&siteId=1