HashMap is already sorted by key?

后端 未结 3 2018
慢半拍i
慢半拍i 2021-01-20 23:39

I thought that HashMap is unordered, and when iterating over the keys, you can\'t know what will be the order? In this example, it looks like the map is already sorted by the ke

相关标签:
3条回答
  • 2021-01-21 00:25

    For small hashCodes, the HashMap turns into an array (as this is what is used underneath) There is no requirement for it to do so but it happens to be the simplest implementation.

    In short, if you add 0 to 10 to a HashSet or HashMap you will get them in order because the capacity is large enough to just layout those values in order.

    0 讨论(0)
  • 2021-01-21 00:27

    Treemap is a sorted map which contains keys in sorted order and HashMap can't gurantee you sorted map.So,always choose Treemap when ever you want sorted keys

    0 讨论(0)
  • 2021-01-21 00:44

    True but there is no guarantee of maintaining that order.

    From Hashmap docs

    This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

    Your bench mark is not enough to decide over it.

    Look at TreeMap If you need the sorting order

    The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used

    0 讨论(0)
提交回复
热议问题