java - HashMap's Iterator to prevent concurrent modification -
this question has answer here:
- iterating on , removing map 12 answers
the following piece of code, while executed single thread, throws concurrentmodificationexception
on line 4:
map<string, string> map = new hashmap<string, string>(); map.put("key1", "value1"); map.put("key2", "value2"); (string key : map.keyset()) { // here map.remove(key); }
i couldn't find map.iterator()
or map.mapiterator()
method on hashmap
javadoc. should do?
as guessed, need iterator
removing items during iteration. way map
iterate entryset()
(or, alternatively, keyset()
, if need evaluate key):
iterator<map.entry<string, string>> entryiter = map.entryset().iterator(); while (iter.hasnext()) { map.entry<string, string> entry = iter.next(); iter.remove(); // guard condition? }
Comments
Post a Comment