According to these:
You can't make assumptions about the orderings on HashMap objects. They will order as they please, implementation-defined. You should treat them as unordered data structures.
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.
You can't assume that it will be sorted. The reason why it appears sorted, in this simple example: A HashMap is internally constructed from "Bins". These Bins contain the actual elements. They are basically small lists that reside in an array.
[0] -> [ Bin0: ... ]
[1] -> [ Bin1: ... ]
[2] -> [ Bin2: ... ]
[3] -> [ Bin3: ... ]
When an item is inserted into the HashMap, then the "Bin" in which it should be inserted is - to simplify it a little - found by using the hashCode()
of the object as an array index. For example, if the hashCode is 2, it will be inserted into Bin 2. When this "index" is greater than the array size, it will be placed into Bin (index%arraySize) - that is, if the hashCode is 5, it will be inserted into Bin 1.
And since a HashMap initially has an internal array size of 10, inserting Integer
objects between 0 and 9 will coincidentally place the elements in the right order into the array. (The hashCode of an Integer is just its value, of course).
(Note: The actual algorithms and hash functions may be slightly more complicated, but that's the basic idea)
It's pure coincidence. Sometimes it appears to be sorted, but keep adding keys and the dream will shatter.
I wrote this little program:
import java.util.Map;
import java.util.HashMap;
class MapTest {
public static void main(String[] args){
int count = Integer.parseInt(args[0]);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < count; i++) map.put(i, i);
System.out.println(map);
}
}
When running java MapTest 20
, I get the following output (line-wrapped for readability):
{0=0, 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}
It's simply a property of the implementation of HashMap
that Integer
s added sequentially (and starting at 0) at first seem to be ordered.
Actually It can not be ensured the order.
Hashmap uses hashcode to hash data for search fast.
Your key is so simple, so it sorted.
It's a coincidence (not really, rather it has to do with the hashing algorithm).
Try adding
newHashMap.put(-5, "Fifth");
as last.
Output will be
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
Key: -5
Value: Fifth
The javadoc specifically says
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.