ConcurrentModificationException while iterating Map

android, concurrency, dictionary, iteration, java

Solution

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.

Problem

I have the following code below ``` Map<String, Integer> buyingItemEnumerationMap = this.toBuyItemEnumeration; for (Entry<String, Integer> item : buyingItemEnumerationMap.entrySet()) { if(RandomEngine.boolChance(50)){ //will delete? buyingItemEnumerationMap.remove(item.getKey()); } if(buyingItemEnumerationMap.size() == 1){ break; } } ``` now I am working with an android game and the code above is running in multithreaded way. Now I am having an exception which is `java.util.ConcurrentModificationException`. I already researched on how I can solve the problem but seems not to work on me. What I am doing on the code above is to remove an entry randomly. How can I implement it there?

Original source

Related problems