0

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();
           }
        }
Kevin Jensen Petersen
  • 423
  • 2
  • 22
  • 43
  • 2
    possible duplicate of [Efficient equivalent for removing elements while iterating the Collection](http://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection) – Rohit Jain Feb 11 '13 at 13:50
  • What do you mean by crash? Do you have NullPointerException? Can you be more explicit about the error you have? – Dimitri Feb 11 '13 at 13:54

1 Answers1

2

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);
    }
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106