Java - 线程“main"中的异常java.util.ConcurrentModificationExce

Java - Exception in thread quot;mainquot; java.util.ConcurrentModificationException(Java - 线程“main中的异常java.util.ConcurrentModificationException)
本文介绍了Java - 线程“main"中的异常java.util.ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有什么方法可以在迭代时修改特定键的 HashMap 值?

下面给出一个示例程序:

public static void main(String[] args) {哈希映射<整数,数组列表<字符串>>hm = new HashMap<Integer, ArrayList<String>>();ArrayListar = new ArrayList<String>();for(int i=0;i<50;i++){ar.add(Integer.toString(i));}hm.put(1, ar);for(字符串 s:hm.get(1)){hm.get(1).add("你好");}}

抛出错误:

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

解决方案

检测到对象的并发修改但不允许修改的方法可能会抛出此异常.

以下代码导致问题.

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

您正在迭代和修改相同的内容.通过创建 new ArrayList

来避免这种情况

 ArrayListar1 = new ArrayList();对于(字符串 s:hm.get(1)){ar1.add("你好");}

阅读这里p>

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 - 线程“main"中的异常java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)