I was wondering how Java orders items in the Map
(HashMap
or Hashtable
) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...?
It's because I've noticed same pairs in the Map
are not always in the same order
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.