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

3

9

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?

Sheba answered 31/5, 2015 at 7:50 Comment(0)
P
11

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.

Preteritive answered 31/5, 2015 at 7:52 Comment(1)
Would it be so unreasonable to default to a null value? Imagine you want a WeakSet by calling WeakHashMap.keySet - sure it's possible with Collections.newSetFromMap, but that's not very intuitive.When
B
2

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.

Billow answered 31/5, 2015 at 7:53 Comment(0)
C
2

It's because each key in the set is linked to a value in the map. Removing a key will remove the associated value, but to add you'll need a value and not just a key.

Categorical answered 31/5, 2015 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.