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

Regarding the Map<K,V> interface:

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

+5
source share
3 answers

Set returned by keySet is supported by Map , so changes to the map are reflected in the set, and vice versa. This means that calling remove on this Set removes the corresponding Entry from the Map .

It makes no sense to call add or addAll on this Set , since you cannot add the [s] key without the corresponding [s] value in Map .

+11
source

Think about what you are asking for:

you want to receive all KEYS of the card (and this set is not a β€œcopy” of keys, it represents the keys of the card).

And then you ask to add items to these KEYS. In other words: the β€œdataset” that you are viewing has the semantic meaning of the keys coming from the card. And you want to increase this "data set" - but without providing the relevant records for this card.

Removal, on the other hand, is straightforward; deleting a key will also delete the corresponding entry from the card.

+2
source

This is because each key in the set is associated with a value on the map. Removing a key will delete the associated value, but to add it, you need a value, not just a key.

+2
source

All Articles