Reputation: 10619
i have the following code:
public List<String> processMap(Map<String, String> aMap) {
Cloner cloner = new Cloner();
Map<String, String> tempMap = cloner.deepClone(aMap);
while(!tempMap.isEmpty()) {
Iterator<Entry<String, String>> iterator = tempMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, String> entry = iterator.next(); // !!!
}
}
return null;
}
To deep copy the map i use this library: Cloner
I marked the line where i unfortunately get a ava.util.ConcurrentModificationException
with '!!!'
Can you please tell me why i get this exception?
The complete code:
Cloner cloner = new Cloner();
Map<String, FreebaseType> tempFreebaseTypes = new HashMap<String, FreebaseType>();
Map<String, FreebaseType> freebaseTypesCopy = cloner.deepClone(freebaseTypes);
while(!freebaseTypesCopy.isEmpty()) {
Iterator<Entry<String, FreebaseType>> iterator = freebaseTypesCopy.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, FreebaseType> entry = iterator.next();
if(tempFreebaseTypes.containsKey(entry.getValue().getSuperType()) || entry.getValue().getSuperType() == null) {
tempFreebaseTypes.put(entry.getValue().getType(), entry.getValue());
freebaseTypesCopy.remove(entry.getKey());
}
}
}
List<FreebaseType> sortedFreebaseTypes = new ArrayList<FreebaseType>();
Iterator<Entry<String, FreebaseType>> iterator = tempFreebaseTypes.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, FreebaseType> entry = iterator.next();
sortedFreebaseTypes.add(entry.getValue());
}
return sortedFreebaseTypes;
Upvotes: 1
Views: 2790
Reputation: 69783
While you iterate a map with an iterator, you are not allowed to modify the map directly, or you get a ConcurrentModificationException
. The only way to modify the map is indirectly through the iterators remove() method, which removes the entry the iterator is currently pointing to from the map.
Replace the line
freebaseTypesCopy.remove(entry.getKey());
with
iterator.remove();
and the code should work.
Upvotes: 2