【发布时间】:2011-08-30 20:41:22
【问题描述】:
我将HashMap 称为testMap,其中包含String, String。
HashMap<String, String> testMap = new HashMap<String, String>();
在迭代map时,如果value与指定的字符串匹配,我需要从map中移除key。
即
for(Map.Entry<String, String> entry : testMap.entrySet()) {
if(entry.getValue().equalsIgnoreCase("Sample")) {
testMap.remove(entry.getKey());
}
}
testMap 包含"Sample",但我无法从HashMap 中删除密钥。
反而得到错误:
"Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)"
【问题讨论】:
-
请始终复制/粘贴代码 sn-ps,而不是键入“类似于”使用的代码。显示的原始代码无法引发运行时异常,因为它是不可编译的。
-
另一个选项虽然很笨拙,但在迭代时创建要删除的对象列表。然后,您可以在初始循环之后创建另一个循环,该循环遍历该列表并将它们从哈希图中删除。
标签: java dictionary