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

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, that's cool and everything, but that didn't really help me alot, since i don't know how to make one of these.
@KevinJensenPetersen check out duplicate posted as a comment under your question .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.