This question is more about design implementation by Java developers. I want to know (if there any vital reason that I cannot think of) why Keyset()
returns a set-view but values()
returns Collection-view
. why not return Values()
as a ValueSet
with set-view
. I can cast to set if needed, but why it is chosen the way it is.
Maybe this could help in deciding what data structures to use when it comes to building our custom ones.
Map<String, Integer> map = new HashMap<String,Integer>();
map.put("hello",1);
map.put("world",2);
Collection <Integer> i = map.values();
Set<String> s = map.keySet();
By definition the keys of a
Map
form aSet
, that is a collection of unique keys. The values of aMap
can be duplicates however. So it is possible to have the same value for different keys in aMap
.