ConcurrentModificationException Woes [duplicate]

末鹿安然 提交于 2019-12-02 15:58:40

问题


I have a method test(), in which I am trying to compare two LinkedHashMaps against each other and modify the contents of one of the maps by removing the key/value pair if it is found in both LHM's. I keep getting a ConcurrentModificationException when running this method. I understand WHY I am getting the exception (since I am trying to modify the list that is being looped over). I'm not sure how to go forth with this however. I have this code so far:

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

}

回答1:


You could use an iterator:

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



回答2:


Instead of removing the elements, put the keys that you want to remove into a separate collection. At the end, traverse that other collection, removing the keys from your map.

Alternatively, use the Iterator interface instead of the for-each loop. This will enable you to use Iterator.remove() to remove elements while iterating.




回答3:


You cannot remove from a list you're currently iterating with a for each. Use the list's iterator to do this.




回答4:


You can use EntrySet's iterator, or save all duplicated keys in another list, and later remove those from the map. Also, do not compare objects using ==, use the equals() function.



来源:https://stackoverflow.com/questions/15811799/concurrentmodificationexception-woes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!