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

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

Can anyone talk about why he says the following?

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

Can the order be changed during re-hashing, therefore?

It would also be nice if you could point me to a resource or a list of collections that exhibit behavior that does not guarantee order in order to remain constant.

AFIK, ArrayList gives such a guarantee (let me know if I'm wrong)

EDIT: "Card Order" = possibly the order in which keys or values ​​are entered.

+8
java hashmap
source share
4 answers

A HashMap has no order - at any time. In fact, it is not used for this purpose. The order may change even if it is not overwritten.

If you need to keep the order constant, use LinkedHashMap

+8
source share

The point of a hashing strategy is to place objects in a pseudo-random manner. He does this so that most of the time only one key / item will be hashed with the given bucket. This allows you to use the search time O (1). When the HashMap or Hashtable grows, the number of buckets changes, and the keys / elements are placed in another pseudo-random way.

The easiest solution to this is to use LinkedHashMap. This will maintain the add order or optional last access order. I prefer to use this collection because it facilitates debugging, because I can predict where the object may be, and sometimes the order in which the object is added may be useful information.

BTW If you are interested in how many orders a small number of keys can order items in a hash collection

+4
source share

For me, the following code:

Map <Integer, Object> map = new HashMap <Integer, Object> (4); map.put (60, null); map.put (48, null); map.put (29, null); System.out.println (map); map.put (47, null); map.put (15, null); map.put (53, null); map.remove (47); map.remove (15); map.remove (53); System.out.println (map); 

outputs:

 {29=null, 48=null, 60=null} {48=null, 29=null, 60=null} 
+3
source share

HashMap has a number of buckets (implemented as an array) in which records are stored.

When an item is added to the map, it is assigned by the bucket based on the value obtained from its hashCode and the size of the HashMap bucket. (Note that it is possible that the bucket is already taken, which is called a collision. This is handled elegantly and correctly, but I will ignore this processing for the description because it does not change the concept).

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

+1
source share

All Articles