JAVACriticalRuntime ErrorMay 16, 2026

Runtime Error

java.util.ConcurrentModificationException: Cannot modify a Collection while it is being iterated over

What This Error Means

This error occurs when a program attempts to modify a collection (like a list or set) while it is being iterated over by a loop or an iterator.

Why It Happens

This error typically happens when a program is iterating over a collection and at the same time, another part of the program is trying to modify the same collection. This can happen when using multi-threading or when using methods like remove(), add(), or clear() on the collection while it's being iterated over.

How to Fix It

  1. 1To fix this error, you can use the following methods: 1) Use a synchronized or thread-safe collection like CopyOnWriteArrayList. 2) Avoid modifying the collection while iterating over it by creating a temporary copy of the collection. 3) Use a for-each loop instead of an iterator if you're using Java 5 or later. 4) Use the Iterator's remove() method to remove elements from the collection while iterating over it.

Example Code Solution

❌ Before (problematic code)
Java
import java.util.ArrayList;
import java.util.Iterator;

class Example {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");

        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            list.remove(0); // This will cause the ConcurrentModificationException
        }
    }
}
✅ After (fixed code)
Java
import java.util.ArrayList;
import java.util.Iterator;

class Example {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");

        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            iterator.remove(); // Using the Iterator's remove() method
        }
    }
}

Fix for java.util.ConcurrentModificationException: Cannot modify a Collection while it is being iterated over

Related JAVA Errors

Related JAVA Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error