ConcurrentModificationException Woes

时间:2013-04-04 12:53:36

标签: java linkedhashmap concurrentmodification

我有一个方法test(),其中我试图将两个LinkedHashMaps相互比较,并通过删除键/值对来修改其中一个映射的内容(如果在两个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());
            }
        }
    }
}

}

4 个答案:

答案 0 :(得分:2)

不是删除元素,而是将要删除的键放入单独的集合中。最后,遍历其他集合,从地图中删除键。

或者,使用Iterator接口而不是for-each循环。这样您就可以在迭代时使用Iterator.remove()删除元素。

答案 1 :(得分:1)

您无法从当前正在迭代的列表中删除每个列表。使用列表的迭代器来执行此操作。

答案 2 :(得分:1)

您可以使用迭代器:

for (Iterator<Entry<String, BigDecimal>> it = testBene.entrySet().iterator(); it.hasNext();) {
    Entry<String, BigDecimal> beneKeySet = it.next();
    if (testDly.containsKey(beneKeySet.getKey())) {
        for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) {
            if ((dlyKeySet.getKey() == beneKeySet.getKey()) && dlyKeySet.getValue() == beneKeySet.getValue()) {
                it.remove();
            }
        }
    }
}

答案 3 :(得分:0)

您可以使用EntrySet的迭代器,或将所有重复的密钥保存在另一个列表中,然后从地图中删除它们。另外,不要使用==比较对象,请使用equals()函数。