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?
why there is difference in the order of the keys ?
Because:
the Java specs (i.e. the javadocs) do not specify the order of a HashMap's keyset, and
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.
Ordering is not guaranteed as per spec. Individual VM's are free to implement whatever they choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With