简体   繁体   中英

Removing object from ArrayList in Java

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();
           }
        }

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM