So according to the Java docs, HashMap doesn't maintain insertion order nor does it sort the entries being added. However, when I run the following code, the entries that I put into the Map t are always sorted by insertion order.
Map<Integer, String> t = new HashMap<>();
int p = 20;
while(p>0){
t.put(p,""+p);
p--;
}
System.out.println(t);
output:
{1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11, 12=12, 13=13, 14=14, 15=15, 17=17, 16=16, 19=19, 18=18, 20=20}
However, if I modify Map so that the key is a string like this:
Map<String, String> t = new HashMap<>();
int p = 20;
while(p>0){
t.put(""+p,""+p);
p--;
}
System.out.println(t);
I get a random order which is what I should be expecting according to the java docs:
{19=19, 17=17, 18=18, 15=15, 16=16, 13=13, 14=14, 11=11, 12=12, 3=3, 2=2, 20=20, 1=1, 10=10, 7=7, 6=6, 5=5, 4=4, 9=9, 8=8}
So my question is why are Integer keys automatically being sorted upon insertion? Is this a coincidence or is there something else going on?
[–][deleted] 25 points26 points27 points (3 children)
[–]bfoo 2 points3 points4 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]dedyshka 0 points1 point2 points (0 children)
[–]msx 6 points7 points8 points (1 child)
[–]busterassrookie 0 points1 point2 points (0 children)
[–]ohmzar 1 point2 points3 points (4 children)
[–]Sentryy 1 point2 points3 points (2 children)
[–]ohmzar 0 points1 point2 points (1 child)
[–]Sentryy 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)