First of all, LinkedHashMap
ordered, but not sorted. TreeMap
sorted (and therefore ordered).
However, you cannot expect the output of keySet()
and values()
be sorted. Javadoc actually says nothing about the order (as it turned out, the order is guaranteed by JavaDoc: Is the order guaranteed to return keys and values ββfrom the LinkedHashMap? ) of these collections, however, looking at the implementation, they must follow the order of the base Map
.
To move on to the recent editing of your question: it is not part of the contract, in fact LinkedHashMap
does not even implement keySet()
and values()
, but uses the base classes ( HashMap
). Although based on the implementation, you can see that the order is saved, you should not depend on it if you want your application to be portable.
source share