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

前端 未结 7 1338
星月不相逢
星月不相逢 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条回答
  • 2020-11-27 14:58

    java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.

    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.

    java.util.LinkedHashMap uses insertion-order.

    This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

    java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.

    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)
提交回复
热议问题