我有一个方法 test(),其中我尝试将两个 LinkedHashMap 相互比较,并通过删除键/值对(如果在两个 LHM 中找到)来修改其中一个映射的内容。运行此方法时,我不断收到 ConcurrentModificationException。我明白为什么我会收到异常(因为我正在尝试修改正在循环的列表)。然而我不知道如何继续下去。到目前为止我有这个代码:
private void test() {
LinkedHashMap<String, BigDecimal>testBene = new LinkedHashMap<String, BigDecimal>();
LinkedHashMap<String, BigDecimal>testDly = new LinkedHashMap<String, BigDecimal>();
testBene.put("ABCDEFG", BigDecimal.ZERO);
testBene.put("BCDEFGH", BigDecimal.ONE);
testBene.put("CDEFGHI", BigDecimal.TEN);
testDly.put("BCDEFGH", BigDecimal.ONE);
testDly.put("Foo", BigDecimal.TEN);
testDly.put("Bar", BigDecimal.TEN);
for (Entry<String, BigDecimal> beneKeySet : testBene.entrySet()) {
if (testDly.containsKey(beneKeySet.getKey())) {
for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) {
if ((dlyKeySet.getKey().equals(beneKeySet.getKey())) &&
dlyKeySet.getValue().equals(beneKeySet.getValue())) {
testBene.remove(dlyKeySet.getKey());
}
}
}
}
}
最佳答案
不要删除元素,而是将要删除的键放入单独的集合中。最后,遍历其他集合,从 map 中删除键。
或者,使用 Iterator
接口(interface)而不是 for-each 循环。这将使您能够使用 Iterator.remove()
在迭代时删除元素。
关于java - 并发修改异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811799/