Zeepblok
Zeepblok

Reputation: 133

Removing stuff from ArrayList with iterator while its still being used

I have made a little game which draws enemies on the screen, the enemies are from an ArrayList. The screen gets redrawn so that the enemies can also move. I do this with this code:

for (Meteor m : getMeteorArrayList()) {
    if (m.getVisible())
    {
        canvas.drawBitmap(m.getImg(), m.getX(), m.getY(), p);
    }
    else
    {
        Iterator<Meteor> iter = getMeteorArrayList().iterator();
        while (iter.hasNext())
        {
            if (iter.next() == m)
            {
                iter.remove();
            }
        }

    }

}

But this gives a problem. If I kill an enemy, I want it to be removed from the ArrayList. I know I can set it to NULL but then it still exists. I use an Iterator for this as you can see in the code above.

The problem with this is that if the screen is redrawn after I removed an enemy the application crashes with this error:

java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)

I think it is because I suddenly have a hole in my ArrayList on the place where the enemy was. How can I make it so that I can remove something from the ArrayList and still access the rest ?

Upvotes: 2

Views: 77

Answers (2)

Blackbelt
Blackbelt

Reputation: 157487

I would use only the iterator

Iterator<Meteor> iter = getMeteorArrayList().iterator();
while (iter.hasNext()) {
    Metor m = iter.next();
    if (m.getVisible()) {

    } else {

    }
}

the exception is probably caused because you are iterating twice over the same list

Upvotes: 1

Eran
Eran

Reputation: 394136

Your problem is that you are iterating over the list twice - once implicitly (with the enhanced for loop) and a second time with an explicit iterator. If you only use an explicit iterator, you'll be able to remove the element from the list.

    Iterator<Meteor> iter = getMeteorArrayList().iterator();
    while (iter.hasNext ()) {
        Meteor m = iter.next ();
        if (m.getVisible()) {
            canvas.drawBitmap(m.getImg(), m.getX(), m.getY(), p);
        } else {
            iter.remove();
        }
    }

Upvotes: 5

Related Questions