Reputation: 133
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
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
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