HashMap in question index calculated according to the hash value? ? ?

1. The procedure of the index key request

// 先用key求得hash值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 利用上述函数求取hash值后 然后(n-1)& hash
int hash = hash(key);
index = (n - 1) & hash;

2. Why initialize the array size is 2 to the power of HashMap, HashMap most efficient? ? ?
First, the HashMap is to obtain the index value by (n-1) & hash manner, power if n is not 2, assuming n = 15, then the (n-1) binary bits 1110, the hash will be ANDed with 1110, then the last one is always 0, and 0001,0011,0101,1001,1011,0111,1101 position these elements can not be stored forever, and controls a large waste, which increases the probability of collision, reducing the efficiency of the query.

3. Why resize to 2 times the original?
When exceeding the limit will resize, using the power of 2 extension, civilian elements either in situ, either before moving power of 2 position in the original position, and therefore, when the expansion of the HashMap, does not need to recalculate the hash, you need only the new look at the original hash value whether it is a 0, 0 if the index is not changed, if it is 1, the index becomes the original index + oldgap, eliminating the need for time to recalculate the hash value

Guess you like

Origin blog.csdn.net/reuxfhc/article/details/82707776