I am making a 2D and currently working on shooting with bullets. The bullet is a seperate class. All the bullets are stored in an arraylist called bullets. I am trying to make it destroy itself when it is out of the side of the screen (< -16), but when I try it gives me this error.
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at GameCanvas.updateMovement(GameCanvas.java:94)
at GameCanvas.gameLoop(GameCanvas.java:63)
at GameCanvas.<init>(GameCanvas.java:28)
at GameClient.<init>(GameClient.java:68)
at GameClient.main(GameClient.java:29)
I assume it has something do with when it is being destroy, I am using this code to destroy it:
public void move() {
if(x > -16) {
x -= move_speed;
} else {
kill();
}
}
public void kill() {
ObjectHandler.bullets.remove(this);
}
updateMovement() method:
public void updateMovement() {
PlayerObject.update();
for(Bullet bullet : ObjectHandler.bullets) {
bullet.move();
}
}
Why is it doing this? Thanks.
This happens because you are modifying a list while you’re iterating over it.
Try to “remember” what you need to
killand after you’ve passed the whole list, go through your “memory” and perform the appropriatekills. This way you will modify the list after iterating over it.E.g.: