Why HashMap length is a power of 2

In order to allow efficient access HashMap, less impact as possible, that is to try to put the data is evenly distributed. We also talked about over the top, range Hash value to the value of -2147483648 2147483647, probably add up to around 4 billion mapping space, as long as the hash function mapping was more evenly loose, general application is difficult to occur collision. But the problem is an array of four billion length, the memory is not fit. So the hash value can not be directly used with. Also the length of the array do first modulo operation before use, in order to obtain the remainder to be stored is the position corresponding to the array index. This array subscript is calculated by "  (n - 1) & hash." (N array representing length). This also explains why HashMap length is a power of two.

How does this algorithm should design it?

First, we might think of using modulo operation% to achieve. However, the focus here: "modulo (%) the operation if the divisor is a power of 2 is equivalent to a reduction of its divisor AND (&) operation (i.e. hash% length == hash & (length -1) provided that the length is the n-th power of 2;). "  and  binary bit operation &,% with respect to the operation efficiency can be improved, which explains why HashMap length is a power of two.

Published 89 original articles · won praise 32 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41345773/article/details/104948877