javahashmap

Is the order of values retrieved from a HashMap the insertion order


I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same.

import java.util.HashMap;

public class HashMapExample {

   public static void main(String[] args) {
       HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
       hashmap.put(1, "apple" );
       hashmap.put(2, "lemon" );
       hashmap.put(3, "orange" );
       hashmap.put(4, "banana" );
       hashmap.put(5, "litchi" );
       hashmap.put(6, "mango" );
       hashmap.put(7, "papaya" );

       System.out.println(hashmap.size());

       for (String key : hashmap.values()) {
           System.out.println(key);
       }
   }
}

output:

7
apple
lemon
orange
banana
litchi
mango
papaya

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in an arbitrary order. This is using Java 6.


Solution

  • The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.

    The HashMap API does not define the order of iteration.

    However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself1.

    In your case, you are using Integer keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.

    In short, what you are seeing is an artifact of the hash table implementation and the specific hashCode method. It is not something that you can (or should) sensibly make use of. Not least because it can change (and has changed) from one Java release to the next!


    1 - Or in Java 8 or later, if congestion of a particular hash bucket / hash chain causes it to switch from a simple list to a red-black tree. Deep implementation detail. If you are curious, read the source code!