Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an iterator with an enhanced for loop in Java?

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.

like image 612
user3304654 Avatar asked Jul 10 '26 00:07

user3304654


1 Answers

In addition to @Codebender answer: to limit the scope of the iterator variable, you can use plain for loop:

for(Iterator<Sprite> it = sprites.iterator(); it.hasNext(); ) {
    Sprite s = it.next();

    ...
    if (s.shouldRemove())
        it.remove();
}

This way the it variable is undefined after the loop.

like image 132
Tagir Valeev Avatar answered Jul 13 '26 08:07

Tagir Valeev