Behavior of LinkedHashMap methods keySet () and values ​​()

Possible duplicate:
Is an order guaranteed to return keySet () on a LinkedHashMap?

We believe that I am creating a LinkedHashMap, for example 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 it give me an ordered set? And if I call values() , are they also ordered?

EDIT

Sry, means ordered, not sorted.

+6
source share
2 answers

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.

+8
source

When you receive a set of keys or values, you do not receive a SortedSet or a sorted collection. However, returned implementations use key / value map iterators and thus return values ​​in insertion order, for example. when used in a foreach loop.

This way you get the order defined by LinkedHashMap , but you cannot assume that it needs to be sorted (and you also cannot use these collections).

+2
source

Source: https://habr.com/ru/post/910071/


All Articles