Video in progress

Strong Middle 🧺 Collections

Why does HashMap do h ^ (h >>> 16) instead of using the key's hashCode() directly?

The bucket index is taken only from the low bits of the hash. XOR-ing the high 16 bits into the low ones keeps keys that differ only in their high bits from piling up in a single bucket.

📖 Answer

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

When the table is small, say 16 buckets, the index is hash & 15, which is the last 4 bits. If the hashes of your keys differ only in the high bits (for example Float values or numbers that are multiples of 65536), they all land in one bucket.

For example, keys whose hashCode() returns 0x10000, 0x20000, 0x30000. The low 16 bits are all zero. Without the XOR they are all in bucket 0. After the XOR the high bits "come down" and they spread out.

Why not a more complex function? The Java 8 authors chose cheap: one shift and one XOR. And treeification protects against heavy collisions.

In an interview this often leads to the question "why is the capacity always a power of 2?". The answer: so that hash & (n - 1) can be used instead of hash % n, which is much faster than division. Even if you write new HashMap<>(100), it is 128 inside.