Look at the source
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
a | = b currency and a = a | b
You can try, if n is a power of 2, it will not change
So why, if the length of a power of 2 it
Hash values range value -2147483648 to 2147483647, probably add up to around 4 billion mapping space. That of course is not directly take.
By mapping only is modulo array. " (n - 1) & hash
." (N array representing the length) which is the formula
Modulo (%) the operation if the divisor is a power of 2 is equivalent to minus its divisor with a premise (&) operation (i.e. hash% length == hash & (length -1) is a length of 2 n-th power;). " And a binary bit operation &,% with respect to the operation efficiency can be improved,
This explains why HashMap length is a power of two.