Say I am iterating over a Map in Java… I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in the Javadoc for the Iterator interface remove method:
[…] The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
I know for sure that I can invoke the remove method without any issues. But while iterating over the Map collection, can I:
-
Change the value associated with a key with the Map class put method (put with an existing key)?
-
Add a new entry with the Map class put method (put with a new key)?
-
Remove an entry with the Map class remove method?
My guess is that I can probably safely do #1 (put to an existing key) but not safely do #2 or #3.
Thanks in advance for any clarification on this.
Best Solution
You can use
Iterator.remove()
, and if using an entrySet iterator (of Map.Entry's) you can useMap.Entry.setValue()
. Anything else and all bets are off - you should not change the map directly, and some maps will not permit either or both of the aforementioned methods.Specifically, your (1), (2) and (3) are not permitted.
You might get away with setting an existing key's value through the
Map
object, but theSet.iterator()
documentation specifically precludes that and it will be implementation specific: