Possible Duplicate:
Is the order guaranteed for the return of keySet() of a LinkedHashMap object?
Consider I create a LinkedHashMap, like the following:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
When I call keySet()
, does that give me an ordered set? And if I call values()
, are these ordered too?
EDIT
Sry, meant ordered, not sorted.
First of all LinkedHashMap
is ordered but not sorted. TreeMap
is sorted (and hence ordered as well).
That being said you can not expect the output of keySet()
and values()
to be sorted. Actually the JavaDoc says nothing about the order (as it turns out, the order is guaranteed by JavaDoc: Is the order guaranteed for the return of keys and values from a LinkedHashMap object?) of these collections, however looking at the implementation they should follow the order of underlying Map
.
To address recent edit to your question: it is not part of the contract, in fact LinkedHashMap
does not even implement keySet()
and values()
but uses base classes's (HashMap
) version. Even though based on the implementation you can see the order is preserved, you should not depend on it if you want your application to be portable.
You don't get a SortedSet
or a sorted collection when retrieving the key set or the values. However, the returned implementations use the map's key/value iterators and thus would return the values in the order of insertion, e.g. when being used in a foreach loop.
Thus you get the order as defined by the LinkedHashMap
but you can not necessarily consider that to be sorted (and you can't resort those collections either).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With