HashMap java.util.ConcurrentModificationException -
i have 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 map use library: cloner
i marked line unfortunately ava.util.concurrentmodificationexception
'!!!'
can please tell me why 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;
while iterate map iterator, not allowed modify map directly, or concurrentmodificationexception
. way modify map indirectly through iterators remove() method, removes entry iterator pointing map.
replace line
freebasetypescopy.remove(entry.getkey());
with
iterator.remove();
and code should work.
Comments
Post a Comment