According to these:
You should not infer too much! Just because three or four numbers appear sorted, it doesn't mean they have been sorted.
The hash code of a positive int is usually just that int, so if all your keys are lower than the length of the internal array the Map maintains, they may appear sorted.
Try with really big values, and you'll see that the apparing order vanishes. For example, use
100,200,300,100001, 100002, 10003, 999123456, 888777666, ....
Since no answer really utilized looking at the Java source, I will do so! :)
When you call the put()
function, the internal hash function uses the hashCode of the object, to generate the hashing index. [put() source]
The hash() function simply ensures that hashCodes that differ only by constant multiples at each bit position have a bounded number of collisions [use Google to see why that is the case].
Things just coincidentally worked here. That is about it.
Mine is an educated guess, but the reason is likely to be the fact that the default hashCode method uses the memory location. The memory location of small Integer
s (and your keys are autoboxed into Integer
) are most likely fixed: it would be nonesense to have Integer.valueOf(1)
return a different memory location on multiple calls. Finally, most likely these fixed memory locations are in the ascending order. This would explain this coincidence, but well, one would need to dig into the implementation of Integer and HashMap to prove this.
Correction: in case of Integer "A hash code value for this object, equal to the primitive int value represented by this Integer object." (JavaDoc). Which, although a different number, confirms the idea.