3

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()
Code Complete
  • 3,146
  • 1
  • 15
  • 38
  • Wouldn't your point about `add(K e)` etc. throwing `UnsupportedOperationException ` be moot since `Set` already provides those methods? Thus even a normal key set would have to implement those methods in the same way. – Thomas Dec 12 '19 at 11:27
  • 2
    Between Java 7 and Java 8, the `ConcurrentHashMap.keySet()` method did change from returning `Set` to returning `ConcurrentHashMap.KeySetView`. This is a covariant override, since `KeySetView` implements `Set`. The question can be stated as why this did change in `java 8`. – Kamil Witkowski Dec 12 '19 at 11:27
  • If the designer/implementors don't post here, someone would have to dig into the code to answer the question – Curiosa Globunznik Dec 12 '19 at 11:41
  • ConcurrentHashMap chm = new ConcurrentHashMap<>(); chm.put("one", 1); chm.put("two", 2); Set set = chm.keySet(); set.add("three"); // UnsupportedOperationException – Code Complete Dec 12 '19 at 11:43
  • some related discussion on this thread: https://stackoverflow.com/questions/32054517/concurrenthashmap-newkeyset-vs-collections-newsetfrommap – sudipn Dec 12 '19 at 11:51

0 Answers0