-->

ConcurrentModificationException的愁楚[复制](ConcurrentM

2019-08-19 12:05发布

这个问题已经在这里有一个答案:

  • 迭代整个集合,避免ConcurrentModificationException的在一个循环中删除对象时 23个回答

我有一个方法试验(+),其中我试图来比较两个互相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());
            }
        }
    }
}

}

Answer 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();
            }
        }
    }
}


Answer 2:

除删除元素,把要删除到单独的收集钥匙。 最后,遍历其他集合,请从地图中删除键。

或者,使用Iterator接口代替for-each循环。 这将使您能够使用Iterator.remove()而迭代删除元素。



Answer 3:

你不能从你目前正与每个迭代一个列表中删除。 使用列表的迭代器来做到这一点。



Answer 4:

您可以使用的entrySet迭代器,或保存所有复制的钥匙,另一份清单,后来又删除那些从地图。 另外,不要使用比较==对象,使用了equals()函数。



文章来源: ConcurrentModificationException Woes [duplicate]