Java - Exception in thread “main” java.util.ConcurrentModificationException

后端 未结 7 1678
广开言路
广开言路 2021-01-07 14:54

Is there any way I can modify the HashMap values of a particular key while iterating over it?

A sample program is given below:

public st         


        
7条回答
  •  一生所求
    2021-01-07 15:47

    Although not related to the question, but just adding

    ConcurrentModificationException can also occur if you get the iterator over a collection first and then add some more elements over it and then iterating over the collection will throw this exception.

    For example :

    package got;
    
    import java.util.*;
    
    public class GotCharacters {
    
    
        public static void main(String... args){
    
            Person p1 = new Person("TL", 40, "Tyrion Lannister");
            Person p2 = new Person("JM", 50, "Jorah Mormont");
            Person p3 = new Person("AS", 20, "Arya Stark");
    
            //Defining the collection and adding some elements
            ArrayList al;
            al = new ArrayList();
            al.add(p1);
            al.add(p2);
            al.add(p3);
    
            //Getting the iterator
            Iterator itr = al.iterator();
    
            Royalty r1 = new Student("DT", 25, "Daenerys Targaryen", "DragonMother", "Targaryen");
            Royalty r2 = new Student("JS", 28, "Jon Snow", "Lord Commander", "Targaryen");
            Collection c = new ArrayList();
            c.add(s1);
            c.add(s2);
    
            //Adding more elements after getting the iterator
            al.addAll(c);
    
            while(itr.hasNext()){
                System.out.print(itr.next());
            }
        }
    }
    

    Outcome :

    Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
        at java.util.ArrayList$Itr.next(ArrayList.java:851)
        at myArrayList.ArrayList1.main(ArrayList1.java:34)
    

提交回复
热议问题