Home >Java >javaTutorial >How Can I Avoid ConcurrentModificationException When Iterating and Modifying a Java List?

How Can I Avoid ConcurrentModificationException When Iterating and Modifying a Java List?

DDD
DDDOriginal
2024-11-29 13:25:11494browse

How Can I Avoid ConcurrentModificationException When Iterating and Modifying a Java List?

Understanding the Concurrent Modification Exception in Java

The ConcurrentModificationException occurs when multiple threads concurrently modify a mutable collection, often violating its internal consistency. To illustrate this concept, let's analyze a code snippet that encounters this exception.

import java.util.*;

public class ConcurrentModificationExample {

    public static void main(String[] args) {
        List<String> s = new ArrayList<>();
        ListIterator<String> it = s.listIterator();

        for (String a : args)
            s.add(a);

        if (it.hasNext())
            String item = it.next();

        System.out.println(s);
    }
}

This code attempts to iterate through a list while adding elements to it. However, the exception is thrown because the ListIterator was created before the elements were added.

To avoid this error, we can modify the code as follows:

import java.util.*;

public class ConcurrentModificationExample {

    public static void main(String[] args) {
        List<String> s = new ArrayList<>();

        for(String a : args)
            s.add(a);

        ListIterator<String> it = s.listIterator();    
        if(it.hasNext()) {  
            String item = it.next();   
        }  

        System.out.println(s);

    }
}

In this revised code, the list iterator is created after the elements have been added to the list, ensuring consistency. A ListIterator allows modification of the list during iteration, but it is crucial that it is created after the list is initialized and not modified between creation and use. This ensures that the list remains in a valid state throughout the iteration.

The above is the detailed content of How Can I Avoid ConcurrentModificationException When Iterating and Modifying a Java List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn