According to these:
Like every one is saying (AND is right about) is that you should assume that the keys in an HashMap are not sorted.
Now they LOOK
sorted in your case for two simple reasons:
1 - You are using Integer as a key: The HashMap
use the hashCode()
method of the Object class of Java to find the index in the underlying array it uses to store the Entry
instances (what contains your values and keys in the HashMap
). It just so happen that the hashcode of an Integer
is its own value.
2 - You are not setting the initial size of the HashMap
and thus are using its default initial size (which is 16). So until you add a key below 0 or above 16 (included) you will see the keys stored in order. Since the HashMap
gets the index by doing
int index = newKey.hashCode() % this.capacity;
Later on HashMap
might increase the capacity of its underlying array if you insert a lot key-value pairs (how and when it decides to do that is very interesting if you are into algo and data structure study), so you might end up in a situation in which your Integer
keys might look sorted again, but they actually are not intentionally sorted.
Btw if your keys are going to be Integers and you can estimate the maximum key value you are going to have I'd suggest to directly use an array. Access is faster and the memory used will be the same or slightly less.