I'm having issues getting the logic behind using an iterator. I need to be able to remove elements from an ArrayList inside the loop, so I thought I'd use an Iterator object. However, I'm not sure how I can transform my original 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's possible that actor or opponent "dies" and
// should be removed from the list that's being looped
}
}
}
I understand that I'd have to use while-loops, which would work for the first loop. But how can you convert the second loop's conditions to something that works with an Iterator? This post says you can obtain the iterator at any point, but in the documentation I can't find anything such as a .get
method.
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's possible that actor or opponent "dies" and
// should be removed from the list that's being looped
// If the actor dies, the outer loop should skip to the next element
}
}
}
Final question: if you access an element in an iterator, that element isn't a copy of the original one, right? In other words, I can set properties to that element, and then access those changed properties by accessing the original Collection?
As Eran pointed out, this might not be as straight forward as it seems because the two loops traverse the same list and might interfere with one another. The question is, then, how do I solve this issue?