Skip to content Skip to sidebar Skip to footer

Concurrentmodificationexception While Iterating Map

I have the following code below Map buyingItemEnumerationMap = this.toBuyItemEnumeration; for (Entry item : buyingItemEnumerationMap.e

Solution 1:

You cannot remove an element from a collection while iterating it unless you use an Iterator.

This is what's causing the exception.

buyingItemEnumerationMap.remove(item.getKey());

Use Iterator#remove() to remove an element while iterating over your collection like

Iterator<Map.Entry<String, Integer>> iterator = 
                           buyingItemEnumerationMap.entrySet().iterator();
while (iterator.hasNext()) {
   Map.Entry<String, Integer> item = iterator.next();
   if(RandomEngine.boolChance(50)){ //will delete?iterator.remove();
   }
   //..
}

EDIT : (in response to OP's comment) Yes, the deletions done through Iterator#remove() over the Set returned by HashMap.entrySet() would reflect in the underlying Map as the Set is backed by it. Quoting the JavaDoc here:

Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Solution 2:

Use Iterator.

Iterator<Map.Entry<String, Integer>> iter = this.toBuyItemEnumeration;
while (iter.hasNext()) {
    Map.Entry<String, Integer> entry = iter.next();
    if (some-condition){
        iter.remove();
    }
}

HOW IT WORKS ?

The javadoc for ConcurrentModificationException says:

If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

The field int expectedModCount is initiated to be equal to the field protected transient int modCount = 0; (and this is valid for Collections and Maps), and modCount keeps track of the structural modifications over the object. If modCount at some point of the iteration gets unequal to expectedModCount, then a ConcurrentModificationException is thrown.

With using Iterator to make structural changes over the map/collection (like removing elements), we make sure that the removal operation will be executed properly, e.g. the modCount will be equal to the expectedModCount.

Solution 3:

Use iterator in the forEach loop and use iterator.remove();

Solution 4:

Yes you can't delete entries in a Map while traversing it by it's own property. different approch.

Post a Comment for "Concurrentmodificationexception While Iterating Map"