Okay so in my project for class I'm looking through an ArrayList of my class "Sprite" with an enhanced for loop, and I occasionally need to delete the Sprite that I'm looking at. I'm told I can do this safely (i.e. not deleting the Sprite I'm currently looking at) with Iterators. I looked it up on Oracle's java documentation but I don't really understand it..
Here's my method:
public void forward() {
for (Sprite s : sprites) {
s.move();
for(Sprite x : sprites){
if(s!=x && s.overlaps(x)){
if(s instanceof Razorback && x instanceof Opponent){
x.hit();
}
if(x instanceof Razorback && s instanceof Opponent){
s.hit();
}
}
}
if(s.shouldRemove())
sprites.remove(s);
}
}
if(s.shouldRemove()) is where I need to implement an iterator. If shouldRemove() return true, s needs to be removed from the ArrayList.
Iteratorsremovemethodfor(int i = sprites.size(); i >= 0; i--). Otherwise, it could be a cause ofConcurrentModificationException. Inner loop is fine as is.