Search code examples
javahashmap

Why HashMap does not guarantee that the order of the map will remain constant over time


I was reading about difference between Hashmap and Hashtable here: http://javarevisited.blogspot.sg/2010/10/difference-between-hashmap-and.html

Can anyone throw some light on why it says following?

"5. HashMap does not guarantee that the order of the map will remain constant over time."

Could the order change during re-hashing, that is why?

It would be also nice if you could point me to resource or list of collections who exhibit such behavior of not guaranteeing order to be remain constant.

AFIK, ArrayList gives such gurantee (let me know if I am wrong)

EDIT: 'Order of map' = maybe order in which keys or values are entered.


Solution

  • A HashMap has no order - at any time. It is actually not used for that purpose. The order may change even when not rehashing.

    If you need the order to remain constant, use a LinkedHashMap