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

How to Avoid ConcurrentModificationException When Iterating and Modifying a List?

DDD
Release: 2024-11-25 09:02:10
Original
665 people have browsed it

How to Avoid ConcurrentModificationException When Iterating and Modifying a List?

Concurrent Modification Exception Handling

Problem:

Encountering a Concurrent Modification Exception when iterating over a list, even when no concurrent modifications seem to be occurring.

Implementation:

The code provided creates a list and a list iterator simultaneously. It then adds elements to the list while iterating through it, causing the exception.

import java.util.*;

public class SomeClass {
    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);
    }
}
Copy after login

Solution:

To avoid the exception, modify the code as follows:

import java.util.*;

public class SomeClass {

    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);

    }
}
Copy after login

In this modified code, the list iterator is created after all elements have been added to the list. This ensures that the list is not modified between the creation and use of the iterator.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template