gnreddy gnreddy - 3 months ago 8
Java Question

HashMap implementation in Java. How does the bucket index calculation work?

I am looking at the implementation of

HashMap
in Java and am stuck at one point.

How is the
indexFor
function calculated?

static int indexFor(int h, int length) {
return h & (length-1);
}


Thanks

Answer

It's not calculating the hash, it's calculating the bucket.

The expression h & (length-1) does a bit-wise AND on h using length-1, which is like a bit-mask, to return only the low-order bits of h, thereby making for a super-fast variant of h % length.