gnreddy gnreddy - 1 year ago 93
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);


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download