How to choose subscript hashmap

 

Source:

// Calculate hash value 32

static final int hash(Object key) {

int h;

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

}

Explain: key.hashCode () to get 32-bit hash value shaping

h >>> 16 represents a 16-bit logical right shift, left patch 16 0, corresponds to the high 16-bit 16-bit moves to the low

^ Denotes exclusive OR operation, the same is 0, 1 is different, the probability of 0 and 1 are 1/2

It means that the 32-bit hash of high worth, returns treated 32-bit hash values ​​are different and the low 16-bit or 16-bit operations

 

 

// The length of the hash calculation of array subscript n

if ((p = tab[i = (n - 1) & hash]) == null)

tab[i] = newNode(hash, key, value, null);

Explain: n is the length of the array, n being a power of 2, in the form of binary 10000 ...

N-1 is the form of 1111, with any number of equal phase are less than n-1

1 // move left four get 16

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

Explanation: The left four binary 1 is 10000, the decimal turn, is 2 ^ 4 = 16 power

// size of the array 16 as an initial

newCap = DEFAULT_INITIAL_CAPACITY;

 

 

Question: Why is the array of length 2 ^ n-th power

Answer: Since the 2 ^ n-1 selected array subscript, binary form 2 ^ n-1 to n-1 from the composition, when the phase with the hash value, the number will give less 2 ^ n-1 and The array index is calculated the same low probability

 

 

 

 

Published 42 original articles · won praise 25 · views 70000 +

Guess you like

Origin blog.csdn.net/qq812858143/article/details/103527087