Andrews B Anthony
Andrews B Anthony

Reputation: 1381

HashMap.KeySet() returns keys in different order in Java 7 Java 8

public class TestClass {    

    public static void main(String[] args)
    {
        HashMap<String,Integer> testMap = new HashMap<String,Integer>();
        testMap.put("Key1", 1);
        testMap.put("Key2", 2);
        testMap.put("Key3", 3);
        testMap.put("Key4", 4);
        testMap.put("Key5", 5);
        //[Key2, Key1, Key4, Key3, Key5] //java7
        //[Key2, Key1, Key5, Key4, Key3] //java8
        System.out.println(testMap.keySet().toString());
    }

}

Why there is difference in the order of the keys?

Upvotes: 3

Views: 2994

Answers (4)

Vikash Patel
Vikash Patel

Reputation: 1346

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) 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.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718866

why there is difference in the order of the keys ?

Because:

  1. the Java specs (i.e. the javadocs) do not specify the order of a HashMap's keyset, and

  2. there were major changes to the implementation of HashMap between Java 7 and Java 8.

Those implementation changes (which gave significant performance improvements) resulted in the order of the keyset changing.

But that is not considered a "breaking" change because the keyset order has always been clearly noted as unspecified .... meaning that you should not rely on it.

Upvotes: 4

Kintu Barot
Kintu Barot

Reputation: 320

Hashmap does not maintain order, if you want ordered insertion you can use linkedhashmap :)

Upvotes: 1

Rishi Goel
Rishi Goel

Reputation: 680

Ordering is not guaranteed as per spec. Individual VM's are free to implement whatever they choose.

Upvotes: 2

Related Questions