java - How to remove and add elements to TreeMap while iterating? -


i want write code -

for (map.entry<long, integer> e : map.entryset()){     map.remove(k);     map.put(x, value); } 

but got java.util.concurrentmodificationexception tried use iterator got same exception

explaintion why caused concurrentmodificationexception

map.remove(k); map.put(x, value); 

for-each loop internally create iterator of entryset of map. while iterating on map have modified structure of map putting value again map (map.put(x,value)) cause concurrentmodificationexception.

it explained in documentation -

the iterators returned of class's "collection view methods" fail-fast: if map structurally modified @ time after iterator created, in way except through iterator's own remove method, iterator throw concurrentmodificationexception. thus, in face of concurrent modification, iterator fails , cleanly, rather risking arbitrary, non-deterministic behavior @ undetermined time in future.

how solve this -

you must change change structure of map while iterating, can insert values later, keep temporary map , add once iteration finished job.

map<long, integer> tempmap = new hashmap<>(); (map.entry<long, integer> e : map.entryset()){     map.remove(k);     tempmap.put(x, value); } map.putapp(tempmap); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -