![](/img/trans.png)
[英]In a three for-each imbricated using Map.Entry<String, Map<Date, List<SomeObject>>> when I iterate why I have a Exception in the second for-each loop?
[英]remove any key value that is equal to the string “world” in an instance of LinkedHashMap, using for-each loop and Map.Entry(), but always get error
我试图遍历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
时,无法从Map
删除元素。
如果使用显式Iterator
迭代它们并使用Iterator
的remove()
方法,则可以从键Set
(或条目Set
)中删除元素。
但是,整个循环不是必需的,可以替换为:
msi1.remove("world");
Map
的整个想法是能够有效地定位和删除条目,而无需迭代整个Map
。
当您尝试在该映射上迭代的同一循环中更新映射时,会发生ConcurrentModificationException。 在您的代码片段中,您正在迭代映射msi1并通过删除同一循环中的键来更新它。 您可以像下面这样解决它:
Map<String, Integer> msi1 = new LinkedHashMap<>();
msi1.put("hello", 1);
msi1.put("world", 2);
msi1.put("morning", 3);
Set<Map.Entry<String,Integer>> set = msi1.entrySet();
for(Map.Entry<String, Integer> e : set){
if(e.getKey().equals("world")){
msi1.remove(e.getKey());
}
}
System.out.println(msi1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.