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

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -