Search code examples
javaconcurrentmodification

Concurrent Modification Exception with Objects


I am having trouble with a Concurrent modification exception. I have changed my code to use iterators however I am still getting these issues when I remove an object. My error occurs on the line

theEnemy = (Enemy) EnemyItr.next();

I'm not sure how I would get around this as it is a very important part of the code.

for (Iterator EnemyItr = activeEnemies.iterator(); EnemyItr.hasNext(); ){

    theEnemy = (Enemy) EnemyItr.next(); 
    try {

        try {

            if (theEnemy.x < 0 && theEnemy.y >= 5) {
                activeEnemies.remove(theEnemy);
            }
        } catch (Exception e) {
            System.err.println("Cannot Remove Enemy");
        }

        Enemy.pathFind(Enemy.getXBlockOfEnemy(theEnemy.x), Enemy.getXBlockOfEnemy(theEnemy.y), theEnemy.x, theEnemy.y);

        if (Enemy.right) {
            theEnemy.x += Enemy.speed;
            //System.out.println("right");
            //System.out.println(theEnemy.x + " " + theEnemy.y);
        } else if (Enemy.down) {
            theEnemy.y += Enemy.speed;
            //System.out.println("down");
            //System.out.println(theEnemy.x + " " + theEnemy.y);;
        } else if (Enemy.up) {
            theEnemy.y -= Enemy.speed;
            //System.out.println("up");
            //System.out.println(theEnemy.x + " " + theEnemy.y);
        } else if (Enemy.left) {
            theEnemy.x -= Enemy.speed;
            //System.out.println("left");
            //System.out.println(theEnemy.x + " " + theEnemy.y);
        } else {
            System.out.println("Enemy Lost.");
            //System.out.println(theEnemy.x + " " + theEnemy.y);
        }

        g.drawImage(enemy, theEnemy.x, theEnemy.y, this);
        //System.out.println(Enemy.getXBlockOfEnemy(theEnemy.x));

        //drawing health bar
        if (Input.displayUI) {
            g.setColor(Color.LIGHT_GRAY);
            g.fillRect(theEnemy.x, theEnemy.y - 10, 70, 10);
            g.setColor(Color.RED);
            g.fillRect(theEnemy.x + 2, theEnemy.y - 10 + 1, 68, 8);
            g.setColor(Color.GREEN);
            g.fillRect(theEnemy.x + 2, theEnemy.y - 10 + 1, (int) (.68 * theEnemy.enemylife), 8);
        }

    } catch (ConcurrentModificationException e) {
        theEnemy = null;
    }

}

Solution

  • The only chance to remove an element from a collection while iterating over it is to use the remove() method of the iterator itself. But since this is an optional method you may have to use the suggestions from the other answers here if your iterator doesn't support the remove method.

    In short: use the remove method of the iterator instead of the remove method of the collection itself.