Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap doesn't provide values in the order in which added them

Tags:

java

android

I am putting values in HashMap. But when I am reading values from that HashMap; I am NOT getting those values in the ORDER in which I have added them. Can any-one help me?.

like image 795
Chintan Raghwani Avatar asked Mar 22 '12 14:03

Chintan Raghwani


2 Answers

HashMap doesn't guarantee that the insertion-order is preserved.

Use LinkedHashMap if you need such guarantee.

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).

like image 136
aioobe Avatar answered Sep 29 '22 18:09

aioobe


From the Java documentation:

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.

like image 42
John Doe Avatar answered Sep 29 '22 19:09

John Doe