One projectile colliding with two objects - Array index out of bounds -1

I have a character in a 2D world that shots a projectile. I have a particular case where if there are 2+ objects overlapping, and I shoot them with my character, I get an array index out of bounds exception when I attempt to remove the projectile I shot from a local Array.


    private Iterator<Enemy> enemyIter;
    private Iterator<Bullets> bulletIter;
    private Array<Enemy> enemyList = new Array<Enemy>();
    private Array<Bullets> bulletsList = new Array<Bullets>();


        bulletIter = bulletsList.iterator();            // If bullet touches enemy, remove enemy from enemyList
        
        while(bulletIter.hasNext()) {
            bullets = bulletIter.next();
            enemyIter = enemyList.iterator();
            
            while(enemyIter.hasNext()) {
                enemy = enemyIter.next();

                if (enemy.getBounds().overlaps(bullets.getBounds())) {
                    enemyIter.remove();
                    bulletIter.remove();
                }
            }
        }

The issue happens on the “bulletIter.remove();” near the bottom.

Its an interesting problem because I know it only happens when I have two enemies that are overlapping each other, and I try to shoot them. I assume that the bullet overlaps multiple enemies, and therefore there is an exception when trying to remove the same bullet twice. I assumed that this wouldn’t happen for a single threaded application, so I’m very confused on how to solve this.

Any advice would be greatly appreciated!

Since you have nested the enemy while loop inside the bullet while, looks like there needs to be a way to go to the next bullet if the current one has been removed due to a collision. In this case I think using break; would work.

Adding break after the bullet removal work perfectly!

Thank you so much – I’ve been staring at the screen for too long. Very elegant solution.