gnreddy - 1 year ago 54

Java Question

I am looking at the implementation of

`HashMap`

How is the

`indexFor`

`static int indexFor(int h, int length) {`

return h & (length-1);

}

Thanks

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`

.