I have been studying Java HashMap source code, the part of it which decides in what bucket to put an object and saw this change in Java 7 (8) as compared to Java 6. Additionally I conducted numerous experiments and both expressions yeild the same result:
hash % n
and
hash & (n - 1)
where n - the array length that must be power of 2.
I just cannot figure out why is it true? Is there any theorem or some math laws that prove these statement are equal? Basically I want to understand the inference and prove the equivalence of those two statements.
PS. If n is not a power of 2 number, the equivalence breaks immedeately.
Think about the bits in
(n - 1)ifnis a power of 2 (or((1 << i) - 1), if you want to simplify the constraint onn):If
nis, say, 16 (= 1 << 4), thenn - 1is 15, and the bit representation of15and16(as 32-bitints) are:So just the lowest 4 bits are set in 15. If you
&this with another int, it will only allow bits in the last 4 bits of that number to be set in the result, so the value will only be in the range 0-15, so it's like doing% 16.However, note that this equivalence doesn't hold for a negative first operand:
Ideone demo