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?
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?
On
Think about what you are asking for:
you want to retrieve all KEYS of a map (and that set is not a "copy" of the keys; it represents the keys of the map).
And then you ask to add elements to those KEYS. In other words: the "data set" you are looking at has the semantic meaning of keys coming from a map. And you want to increase that "data set" - but without providing the corresponding entries for that map.
Deletion on the other hand is straight forward; deleting a key will also delete the corresponding entry from the map.
The
Setreturned bykeySetis backed by theMap, so changes to the map are reflected in the set, and vice-versa. This means that callingremoveon thatSetremoves the matchingEntryfrom theMap.It would make no sense to call
addoraddAllon thatSet, since you can't add key[s] without corresponding value[s] to theMap.