Java - 线程“主”中的异常java.util.ConcurrentModificationException [英] Java - Exception in thread "main" java.util.ConcurrentModificationException

查看:669
本文介绍了Java - 线程“主”中的异常java.util.ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以修改特定键的 HashMap 值吗?



示例程序如下:

  public static void main(String [] args){
HashMap& ArrayList< String>> hm = new HashMap< Integer,ArrayList< String>>();
ArrayList< String> ar = new ArrayList< String>();
for(int i = 0; i <50; i ++){
ar.add(Integer.toString(i));
}

hm.put(1,ar);

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

}

错误抛出:



线程main中的异常java.util.ConcurrentModificationException
at java.util.ArrayList $ Itr.checkForComodification(Unknown Source)
at java.util.ArrayList $ Itr.next(未知源)
在Excp.main(Excp.java:17)


解决方案

当不允许这样的修改时,可能会由检测到对象的并发修改的方法抛出此异常。



下面的代码会导致问题。

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

您正在迭代和修改它。通过创建新的ArrayList

 避免这种情况,ArrayList< String> ar1 = new ArrayList< String>(); 

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

有一个阅读这里


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 static void main(String[] args) {
    HashMap<Integer,ArrayList<String>> hm = new HashMap<Integer, ArrayList<String>>();      
    ArrayList<String> ar = new ArrayList<String>(); 
    for(int i=0;i<50;i++){              
        ar.add(Integer.toString(i));            
    }

    hm.put(1, ar);      

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

}

Error Thrown:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at Excp.main(Excp.java:17)

解决方案

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<String> ar1 = new ArrayList<String>();

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

have a read here

这篇关于Java - 线程“主”中的异常java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆