javadictionarysetkeysetunsupportedoperation

Unsupported add/addAll operations for Map<K,V>.keySet()


Regarding the Map<K,V> interface:

Why does keySet() return a Set that supports the remove operation but doesn't support add() and addAll() operations?


Solution

  • The Set returned by keySet is backed by the Map, so changes to the map are reflected in the set, and vice-versa. This means that calling remove on that Set removes the matching Entry from the Map.

    It would make no sense to call add or addAll on that Set, since you can't add key[s] without corresponding value[s] to the Map.