Convert ArrayList Inline Loop to Iterator

I am having problems with the logic of using an iterator. I need to remove elements from an ArrayList inside a loop, so I decided to use an Iterator object. However, I'm not sure how I can convert the source code to an iterator.

Original loop:

ArrayList<Entity> actorsOnLocation = loc.getActors();
int size = actorsOnLocation.size();

if (size > 1) {
    for(Entity actor: actorsOnLocation) {
        // Loop through remaining items (with index greater than current)
        for(int nextEnt=index+1; nextEnt < size-1; nextEnt++) {
            Entity opponent = actorsOnLocation.get(nextEnt);
            // Here it possible that actor or opponent "dies" and
            // should be removed from the list that being looped
        }
    }
}

I understand that I will have to use while-loops, which will work for the first loop. But how can you convert the conditions of the second loop into what works with Iterator? This post says that you can get an iterator at any time, but in the documentation I can not find anything like a method .get.

ArrayList<Entity> actorsOnLocation = loc.getActors();
int size = actorsOnLocation.size();
Iterator actorsIterator = actorsOnLocation.iterator();

// How to get size of an iterator?
if (size > 1) {
    while(actorsIterator.hasNext()) {
        Entity actor = (Entity) actorsIterator.next();
        // How to get current index?
        int index = actorsIterator.indexOf(actor);
        // How to convert these conditions to Iterator?
        for(int nextEnt=index+1; nextEnt < size-1; nextEnt++) {
            Entity opponent = actorsOnLocation.get(nextEnt);
            // Here it possible that actor or opponent "dies" and
            // should be removed from the list that being looped

            // If the actor dies, the outer loop should skip to the next element
        }
    }
}

: , , ? , , , ?

, , , . , ?

+4
2

, ""

ListIterator<T>, , . ConcurrentModificationException.

: , , , :

outerLoop:
for(int i = 0 ; i < actorsOnLocation.length()-1 ; i++) {
    Entity actor = actorsOnLocation.get(i);
    // Loop through remaining items (with index greater than current)
    ListIterator<Entity> oppIter = actorsOnLocation.listIterator(i+1);
    while (oppIter.hasNext()) {
        Entity opponent = oppIter.next();
        // Here it possible that actor or opponent "dies" and
        // should be removed from the list that being looped
        if (opponent.mustDie()) {
            oppIter.remove();
        } else if (actor.mustDie()) {
            // The following operation invalidates oppIter
            actorsOnLocation.remove(i);
            // so we must continue the outer loop
            continue outerLoop;
        }
    }
}
0

iterator() Iterator, .

ListIterator<E> listIterator(int index);

ListIterator, .

0

Source: https://habr.com/ru/post/1621269/


All Articles