How does Java order items in a HashMap or a HashTable?

前端 未结 7 1480
星月不相逢
星月不相逢 2020-11-27 14:31

I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, mem

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:50

    HashMap does not sort at all. For a map that sorts by key values you should use TreeMap instead.

    From the JavaDocs for TreeMap:

    Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.

    From the documentation of HashMap:

    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.

提交回复
热议问题