如何在Java中修改对象时迭代? [英] How can I iterate over an object while modifying it in Java?
问题描述
我试图循环通过 HashMap
:
Map<String, Integer> group0 = new HashMap<String, Integer>();
...并提取 group0
。这是我的方法:
... and extract every element in group0
. This is my approach:
// 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
中删除元素,从而修改其大小,从而导致以下错误:
The problem here is that each call to assign()
will remove elements from group0
, thus modifying its size, thus causing the following error:
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
中的元素,而动态更改?
So... how can I loop through the elements in group0
while it's dynamically changing?
推荐答案
其他人提到了正确的解决方案,并没有实际拼写出来。所以这里是:
Others have mentioned the correct solution without actually spelling it out. So here it is:
Iterator<Map.Entry<String, Integer>> iterator =
group0.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
// 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);
}
// I don't know under which conditions you want to remove the entry
// but here's how you do it
iterator.remove();
}
另外,如果要安全地更改分配函数中的地图,需要传入迭代器(其中只能使用remove函数,只能使用一次)或条目更改值。
Also, if you want to safely change the map in your assign function, you need to pass in the iterator (of which you can only use the remove function and only once) or the entry to change the value.
这篇关于如何在Java中修改对象时迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!