When inserting in ArrayList, Java util. ConcurrentModificationException

See the English answer > how to avoid Java util. Concurrent modificationexception when iterating through and removing elements from an ArrayList

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class MyList {
    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>();

        al.add("S1");
        al.add("S2");
        al.add("S3");
        al.add("S4");

        Iterator<String> lir = al.iterator();

        while (lir.hasNext()) {
            System.out.println(lir.next());
        }

        al.add(2,"inserted");

        while (lir.hasNext()) {
           System.out.println(lir.next());
        }
    }
}

Specific code raises an error:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(UnkNown Source)
    at java.util.ArrayList$Itr.next(UnkNown Source)
    at collections.MyList.main(MyList.java:32)

Solution

This is because the array list was modified after the iterator was created

Documentation

Iterator<String> lir = al.iterator(); // Iterator created

while (lir.hasNext()) 
    System.out.println(lir.next());
al.add(2,"inserted"); // List is modified here
while (lir.hasNext()) 
    System.out.println(lir.next());// Again it try to access list

What should you do here to create a new iterator object after modification

...
al.add(2,"inserted");
lir = al.iterator();
while (lir.hasNext()) 
    System.out.println(lir.next());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>