gnreddy gnreddy - 8 months ago 31
Java Question

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

I am looking at the implementation of

in Java and am stuck at one point.

How is the
function calculated?

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



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.