-->

ConcurrentModificationException Woes [duplicate]

2019-03-03 18:08发布

问题:

This question already has an answer here:

  • Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop 22 answers

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.