If you want an order-preserving map, you should use LinkedHashMap
:
Hash table and linked list implementation of the Map interface, with predictable iteration 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). Note that insertion order is not affected if a key is re-inserted into the map. (A key k
is reinserted into a map m
if m.put(k, v)
is invoked when m.containsKey(k)
would return true immediately prior to the invocation.)
This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap
(and Hashtable
), without incurring the increased cost associated with TreeMap
.
Note that this is usually compared with HashMap
rather than Hashtable
- I don't know of an order-preserving equivalent to Hashtable
; the latter isn't usually used these days anyway (just as ArrayList
is usually used in preference to Vector
).
I've assumed you want insertion order rather than key-sorted order. If you want the latter, use TreeMap
.