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

后端 未结 7 1825
广开言路
广开言路 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:34

    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

    Below peice of code is causing the problem.

    for(String s:hm.get(1)){
            hm.get(1).add("hello");
        }
    

    You are iterating and modifying the same. Avoid this by creating new ArrayList

      ArrayList ar1 = new ArrayList();
    
    for (String s : hm.get(1)) {
                ar1.add("hello");
            }
    

    have a read here

提交回复
热议问题