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

后端 未结 7 1680
广开言路
广开言路 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<Person> al;
            al = new ArrayList<Person>();
            al.add(p1);
            al.add(p2);
            al.add(p3);
    
            //Getting the iterator
            Iterator<Person> 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<Royalty> c = new ArrayList<Royalty>();
            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)
    
    0 讨论(0)
提交回复
热议问题