Photo understand the composition of HashMap
hashMap mainly of type Node arrays, linked lists, red-black tree composition. As can be seen from the figure, Node objects stored in the array, each Node object is associated with a list, if the list of elements to use more than eight red-black tree is stored.
About 2 power
Using the array length -1 modulo hash value for determining a location in Node element array.
tab[i = (n - 1) & hash]
复制代码
The purpose of the source code to do so
In a word using modulo a power of 2 -1 way it is to allow a uniform distribution of elements in the array, using the array space.
The basic idea
n is the length of the array, the value is an n-th power of 2.
Suppose n = 8, hashcode = 0100010001100
(N-1) & hash is calculated as follows:
0100010001100 //hashcode的值
& 0111 //(8-1)=7的二进制代码
0100 //相&之后的值
复制代码
You will find hashcode value 0100010001100
, the value after the phase & 0100
the same back three values, good to do so is to get hashcode low value.
to sum up
Low values obtained in determining the position of the element in the hash array, hash is to improve the utilization of the array.