Why keySet() in ConcurrentHashMap returns KeySetView and not just Set like other Map implementations?

1.1k views Asked by At

Why keySet() in ConcurrentHashMap returns KeySetView<K,V> and not just Set (since Java SE8)?

ConcurrentHashMap.KeySetView<K,V>   keySet()

KeySetView - A view of a ConcurrentHashMap as a Set of keys, in which additions may optionally be enabled by mapping to a common value.

But keySet() does not enable "mapping to a common value" (unlike keySet(V mappedValue)) so I don't see any sense in making it KeySetView<K,V> - boolean add(K e) and boolean addAll(Collection<? extends K> c) methods would always throw UnsupportedOperationException here.

P.S. I know that KeySetView<K,V> extends (is-a) Set<K>. So I can use Set interface as usual.

I also understand that keySet() is free to return whatever class it likes to the Set interface (and we shall not care), but in ConcurrenthashMap that return class is explicitly documented - seemingly for some useful purpose.

Maybe the only use-case here is that KeySetView<K,V> gives access to the backing map:

ConcurrentHashMap<K,V>  getMap()
0

There are 0 answers