Search code examples
javaexceptionarraylistconcurrentmodification

java.util.ConcurrentModificationException displaying when using the correct remove() method


I'm trying to remove an entity when isActive is false. When the entity attribute isActive is set to false, it enters if statement and removes the entity, when iterating through the entities list again after that and then crashes. From what I've researched I am using the correct way to remove an object from an array list.

the code when removing the entity and iterating through the list is

    for (Entity entity : entities) {// itaarate through all the entities in list of entities

        entity.render(shader, camera, this);// render each entity

        if (!entity.isActive())// checks if entity attribute is active
            entities.remove(entity);// removes entity from list

    }

when using the debugger after it removes the entity from the list, it goes back to the top of the for loop and then displays this page

enter image description here

the Variables window when debugging

enter image description here

the full error that displays in the console is

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at project.World.render(World.java:196)
at project.Main.<init>(Main.java:152)
at project.Main.main(Main.java:167)

the list being created is

public static ArrayList<Entity> entities; // contains all entities

Solution

  • You can't change a collection while iterating.

    List<Entity> entitiesToRemove = new ArrayList<>();
    
    for (Entity entity : entities) {
        entity.render(shader, camera, this);
    
        if (!entity.isActive()) {
            entitiesToRemove.add(entity);
        }
    }
    
    entities.removeAll(entitiesToRemove);