EDIT: As of Java 8 and later, the following is no longer applicable. This proves that you shouldn’t rely on undocumented Java behaviours.
This behaviour is caused by several separate reasons:
- Integers hash to themselves
- in Java,
HashMap
s andHashSet
s are backed up by an array - they also modify hashes using the higher bits to modify the lower bits; if the hash is in range 0..15, it’s therefore not modified
- what bucket an object goes depends on the lower bits of the modified hash
- when iterating over a map or a set, the inner table is scanned sequentially
So if you add several small (<16) integers to a hashmap/hashset, this is what happens:
- integer
i
has hashcodei
- since it’s less than 16, it’s modified hash is also
i
- it lands in the bucket no.
i
- when iterating, the buckets are visited sequentially, so if all you stored there are small integers, they will be retrieved in ascending order
Note that if the initial number of buckets is too small, the integers may land in buckets not numbered after them:
HashSet<Integer> set = new HashSet<>(4);
set.add(5); set.add(3); set.add(1);
for(int i : set) {
System.out.print(i);
}
prints 153
.