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

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

    The problem in the code your presented isn't modifying the HashMap, it's modifying the ArrayList while iterating it. You can avoid this exception if you use ar's ListIterator instead of using an enhanced for loop:

    for (ListIterator i = ar.listIterator(); i.hasNext(); i.next()) {
        i.add("hello");
    } 
    

提交回复
热议问题