LinkedHashMap<String,ArrayList<String>> h;
It contains:
key 1 : value 开发者_开发技巧A, B, C, D
2 : E,F
3 : G
I don't quite understand the Set interface. Maybe a little visualization would help. Please help me to visualize how would all these elements inside LinkedHashMap look like once I convert them into Set?
Set set = h.entrySet();
Sorry, maybe my question is a little obscure. I will try to sharpen it as the thread develops.
The entry-set of a Map
is the set of entries in the map.
An entry in a map is a mapping from key to value. In your case where the map is of type ...<String, ArrayList<String>>
, an single entry is a pair of a String
(the key) and an ArrayList<String>
(the value).
The following snippet may shed some light on this:
LinkedHashMap<String, List<String>> map =
new LinkedHashMap<String, List<String>>();
map.put("1", Arrays.asList("A", "B", "C"));
map.put("2", Arrays.asList("E", "F"));
map.put("3", Arrays.asList("G"));
System.out.println(map.entrySet());
System.out.println(map.entrySet().getClass());
Output:
[1=[A, B, C], 2=[E, F], 3=[G]] # All entries (key/value pairs)
class java.util.HashMap$EntrySet # This particular entry set class.
In this case for instance, the entry set is actually an inner class of HashMap
, named EntrySet
.
The entrySet()
is just the entries (key-value pairs) in the map. It would help you to look at the type returned by entrySet()
, which is Set<Map.Entry<String, ArrayList<String>>>
in your example. See the Map.Entry javadoc.
Also note that the map is not converted to an entry set--rather, the entry set is a view of the entries in the map.
As far as what a Set
is: it's a set of elements that are each unique according to some definition of unique (equals
/hashCode
for most Set
s, Comparable
/Comparator
for SortedSet
s). Since a Map
can have at most one value mapped to a single key, each key-value entry is guaranteed to be unique.
精彩评论