How to Resolve ConcurrentModificationException When Iterating Over a List in Java?

Question

What causes ConcurrentModificationException while iterating over a List in Java, and how can I fix it?

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));

for (String item : list) {
    if (item.equals("B")) {
        list.remove(item); // This line will cause ConcurrentModificationException
    }
}

Answer

The ConcurrentModificationException in Java occurs when a collection is modified while iterating over it using an iterator or enhanced for-loop. This exception is a part of the Java Collections Framework and is designed to prevent inconsistent states.

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> iterator = list.iterator();

while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("B")) {
        iterator.remove(); // Safe way to remove item
    }
}

Causes

  • Modifying a list while traversing it using a `for-each` loop or an iterator.
  • Using one collection in one thread while modifying it in another thread without proper synchronization.

Solutions

  • Use `Iterator.remove()` method while iterating through the collection.
  • Use a temporary list to collect items to be removed and delete them after the loop.
  • Utilize concurrent collections like `CopyOnWriteArrayList` for thread-safe modifications.

Common Mistakes

Mistake: Using `list.remove(item)` within a for-each loop.

Solution: Use `iterator.remove()` to safely remove items during iteration.

Mistake: Not checking for thread safety when using multiple threads.

Solution: Consider using concurrent collections like `ConcurrentHashMap` or `CopyOnWriteArrayList`.

Helpers

  • ConcurrentModificationException
  • Java exception handling
  • iterating over list in Java
  • remove from list in Java

Related Questions

⦿How to Prevent JSF from Escaping HTML Content?

Learn how to prevent JSF from escaping HTML by using markup correctly and avoiding common pitfalls. Expert tips and code examples included.

⦿What Are the Advantages of Using BufferedWriter for Appending to Files in Java?

Discover the benefits of using BufferedWriter to append data to files in Java with code examples and best practices.

⦿How to Implement an ActionListener in Java to Detect Button Clicks

Learn how to use ActionListener in Java to detect button clicks effectively. Stepbystep guide with example code snippets.

⦿How to Use a String Array as Values in a HashMap in Java?

Learn how to use a String array as values in a HashMap in Java with examples and best practices. Discover common mistakes and debugging tips.

⦿Understanding the Complexity of the `instanceof` Operator in Java

Learn about the instanceof operator in Java its complexity usage and common mistakes to avoid in your programming.

⦿How to Resolve ClassNotFoundException for javax.servlet.AsyncContext in Jetty Hello World Project in Eclipse?

Learn how to fix ClassNotFoundException javax.servlet.AsyncContext in a Jetty Hello World application using Eclipse. Stepbystep guide for developers.

⦿Understanding Java Generics: How to Fix the Incompatible Type Error (Required String; Found java.lang.String)

Learn how to resolve the Java generics incompatible type error. Stepbystep guide with code examples and common mistakes.

⦿How to Create a JSON String Using JSONObject and JSONArray in Java?

Learn how to efficiently create JSON strings with JSONObject and JSONArray in Java including code examples and common mistakes.

⦿How to Import org.apache.commons.net.ftp.FTPClient in Java

Learn how to import FTPClient from Apache Commons Net library in your Java project. Stepbystep guide included.

⦿How to Resolve Log4j Not Logging Issues in JBoss 6 EAP

Learn how to fix Log4j logging issues in JBoss 6 EAP with detailed troubleshooting steps and code examples.

© Copyright 2025 - CodingTechRoom.com