Why am I getting java.util.ConcurrentModificationException?

前端 未结 7 943
独厮守ぢ
独厮守ぢ 2020-12-19 10:55

As I run the following code :

    import java.util.LinkedList;

    class Tester {
      public static void main(String args[]) {
        LinkedList

        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 11:28

    The ConcurrentModificationException is thrown when iterating through the list and at the same time when you are trying to modify (add/remove) the contents of the list either through another thread or in a loop.

    You can try using ConcurrentLinkedQueue or as John stated do a copy and modify the original in iteration.

    Queue list = new ConcurrentLinkedQueue();
    
    list.add("suhail");
    list.add("gupta");
    list.add("ghazal");
    list.add("poetry");
    list.add("music");
    list.add("art");
    
    int size = list.size();
    
    for(int i = 0; i < size; i++){
        list.add("art");
        list.remove("art");
        System.out.println(list);
    }
    

提交回复
热议问题