Concurrent Modification Exception
When dealing with collections, you may encounter the ConcurrentModificationException, indicating that a collection has been modified while an iterator is in use. This can be a confusing error to debug, especially if you don't see any apparent concurrency in your code.
Consider the following example:
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); } }
In this code, a ConcurrentModificationException is thrown because the list s is modified by adding elements (using s.add()) while the iterator it is created but not yet used.
To resolve this issue, you should create the iterator after the list has been fully populated. Here's a corrected version of the code:
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); } }
This modification ensures that the iterator is created and used after the collection has been fully modified, preventing any concurrency issues.
The above is the detailed content of How to Avoid ConcurrentModificationException When Iterating Through Collections?. For more information, please follow other related articles on the PHP Chinese website!