What basic operations on a Map are permitted while iterating over it?

前端 未结 4 973
既然无缘
既然无缘 2021-01-11 14:21

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

4条回答
  •  终归单人心
    2021-01-11 14:58

    You can use Iterator.remove(), and if using an entrySet iterator (of Map.Entry's) you can use Map.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 the Set.iterator() documentation specifically precludes that and it will be implementation specific:

    If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. (emphasis added)

提交回复
热议问题