可能的重复:
Java:高效等效于在迭代集合时
移除
我正在尝试循环HashMap
:
Map<String, Integer> group0 = new HashMap<String, Integer>();
...并提取group0
. 这是我的方法:
// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {
// determine where to assign 'entry'
iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
if (iEntryGroup == 1) {
assign(entry.getKey(), entry.getValue(), 2);
} else {
assign(entry.getKey(), entry.getValue(), 1);
}
}
这里的问题是每次调用assign()
都会从中删除元素group0
,从而修改其大小,从而导致以下错误:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$EntryIterator.next(HashMap.java:834)
at java.util.HashMap$EntryIterator.next(HashMap.java:832)
at liarliar$Bipartite.bipartition(liarliar.java:463)
at liarliar$Bipartite.readFile(liarliar.java:216)
at liarliar.main(liarliar.java:483)
那么......我如何在group0
动态变化时循环遍历元素?