Reputation: 513
I have this, where everytime a Bullet reaches the position greater than my screen width, it has to be destroyed. When i try this, the game crashes.
"bullet" is my class which contains the i's as objects.
"bullets" is my arraylist, containg all of the objects.
EDIT: Trying with Iterator now, but still still crashes.
EDIT: Accepted answer helped me. Working now. Thanks!
public ArrayList<bullet> bullets = new ArrayList<bullet>();
public Iterator<bullet> it = bullets.iterator();
while (it.hasNext()) {
bullet s = it.next();
if(s.xPosition > screenWidth - 10) {
it.remove();
}
}
Upvotes: 0
Views: 726
Reputation: 46408
You cannot remove elements from your List while iterating over it. you will get ConcurrentModificationException
if you do it.
you should use an iterator and remove elements from the iterator.
Iterator<Bullet> itr = bullets.iterator();
while(itr.hasNext()) {
if(itr.next().xPosition > screenWidth - 10) {
itr.remove(i);
}
}
Upvotes: 2