java - 使用 for-each 循环和 Map.Entry() 删除 LinkedHashMap 实例中等于字符串 "world"的任何键值,但总是出错

标签 java dictionary

我尝试遍历 LinkedHashMap 的一个实例,并使用 for-each 循环和 Map.Entry() 删除等于字符串“world”的任何键值。但是,IDE 总是输出一条错误消息。有人可以提示我为什么会这样吗?在此先感谢您的帮助!

Map<String, Integer> msi1 = new LinkedHashMap<>();

msi1.put("hello", 1);
msi1.put("world", 2);
msi1.put("morning", 3);

for(Map.Entry<String, Integer> e : msi1.entrySet()){

    if(e.getKey().equals("world")){

        msi1.remove(e.getKey());
    }
}

System.out.println(msi1);

错误信息:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:711)
    at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:744)
    at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:742)
    at JTOCollection.MapInterfaceClass2.main(MapInterfaceClass2.java:33)
Java Result: 1

最佳答案

在使用增强的 for 循环迭代时,您不能从 Map 中删除元素。

如果您使用显式Iterator 迭代它们并使用Iteratorremove() 方法。

但是,整个循环不是必需的,可以替换为:

msi1.remove("world");

Map 的整体理念是能够通过其键有效地定位和删除条目,而无需遍历整个 Map

关于java - 使用 for-each 循环和 Map.Entry() 删除 LinkedHashMap 实例中等于字符串 "world"的任何键值,但总是出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36077712/

相关文章:

java - Android LocationListener 崩溃

java - 选择列表中的项目后在面板上设置标签

java - 如何使我的 ArrayList 线程安全? Java中解决问题的另一种方法?

map 上的 HTML "doughnut"

python - 在 Python 中制作菜单

java - 在 64 位机器上访问硬件 PKCS11 token

java - Flying Saucer - ITextRenderer createPdf 速度极慢

c# - 字典 trygetvalue null

python - 合并两个字典

python - 如何在 Python 中设置字典的初始大小?