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

1

8

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();
Squaw answered 3/1, 2014 at 21:15 Comment(1)
Would guess it's because they expect values could be a list or data structure with duplicates in itDymoke
A
17

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.

Anyway answered 3/1, 2014 at 21:16 Comment(1)
Glad to help you friend.Anyway

© 2022 - 2024 — McMap. All rights reserved.