I was going through the introduction of Hash Map in Java and I came across that Hash Maps are unordered and unsorted. So we should get the mappings in an arbitrary order of the keys when printing the using System.out.println(HM). For example, the following code
HashMap<Integer,String> HM = new HashMap<>();
HM.put(16,"hello16");
HM.put(6, "hello6");
HM.put(1, "hello1");
prints {16=hello16, 1=hello1, 6=hello6} which is an apparently random order of keys. But when I replace the HM.put(16,"hello16"); with HM.put(15,"hello15");, it prints the mappings in the natural order of the keys, which is surprising and seems unlikely by chance:
{1=hello1, 6=hello6, 15=hello15}
I asked a friend and he said that it's related to the initial capacity (=16) of the HashMap but he couldn't explain it clearly. Can anyone explain this difference in the output with this particular example.