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