gnreddy - 5 months ago 13

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

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`

.