-1

I'm making a basic game in java. In the game you are a block and by using the keys(up, down etc) you should shoot the enemies. Which also is a block. I have a working collision between the two objects and it works. However, when the bullet hits the enemy it should go away. And when all enemies are "killed" you win. This is basicly what I got so far.

ArrayList<Enemy> enemy;
ArrayList<Bullet> bullets;

[...]

public void collision (){

    for(Bullet b : bullets){

        Rectangle r1 = b.getBounds();

        for(Enemy e : enemy){

            Rectangle r2 = e.getBounds();

            if(r1.intersects(r2)){

                enemy.remove(e);

            }

        }

    }

The Enemies are spawned by a .txt

else if(mark == 'E'){
    enemies.add(new Enemy(x * 20 + 10, y * 20 + 35, 40));
}

So when you hit the enemies with a bullet i get a java.util.ConcurrentModificationException firstly at for(Enemy e : enemy){

However if I hit the enemies in a specific order I am able to delete all but 1 enemy. And then the error occurs. The collision method is placed in the "gameloop".

Tonton
  • 63
  • 1
  • 7

1 Answers1

7

You cannot remove from a list being iterated, unless the removal is done through the list iterator itself.

Change your code to iterate explicitly (rather than using the "for each" form of the for loop), create an iterator for enemies, and call enemyIterator.remove() to avoid this problem:

ListIterator<Enemy> enemyIterator = enemy.listIterator();
while (enemyIterator.hasNext()) {
    Rectangle r2 = enemyIterator.next().getBounds();
    if(r1.intersects(r2)) {
        enemyIterator.remove();
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523