Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 933
Andrews B Anthony Avatar asked Sep 28 '26 09:09

Andrews B Anthony


2 Answers

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.

like image 121
Stephen C Avatar answered Oct 02 '26 06:10

Stephen C


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

like image 41
Rishi Goel Avatar answered Oct 02 '26 07:10

Rishi Goel