According to these:
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 map = new HashMap();
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.