java - HashMap's Iterator to prevent concurrent modification -


this question has answer here:

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

Popular posts from this blog

gcc - MinGW's ld cannot perform PE operations on non PE output file -

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

c# - Search and Add Comment with OpenXML for Word -