why map.keyset() returns set view but map.values() returns collections in Java?

1.7k views Asked by At

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();
1

There are 1 answers

1
Meno Hochschild On BEST ANSWER

By definition the keys of a Map form a Set, that is a collection of unique keys. The values of a Map can be duplicates however. So it is possible to have the same value for different keys in a Map.