Today I saw HashMap, and found one of the methods is very strange, called indexfor (int h, int length), this method returns a hashcode corresponding to the hash table subscript position, the code is so implemented:
static int indexfor (int h, int length) {return
H & (length-1);
}
Read for a long time to understand why so write, in fact, hashmap in the data or array, when put value to map is to add data to the array, but the location of the data according to the key to calculate. Before learning Hashtable, the calculation position is used hashcode%length. But that's not how it's done in HashMap.
Let's assume that the length of the HashMap is now 16, and the first Hashcode value is 7., then according to the code above, the calculation process should be:
7& (16-1)
The conversion to binary is calculated by:
0111
&
1111
The result of the calculation is 111, which is 7, and we find that this value is consistent with the result of 7%16. Let's test another hashcode for 33.
The binary calculation process is:
100001
&
001111
The calculated result is 000001, which is the same as the 33%16 result.
After several simulations, it can be found that each digit in the binary value of length-1 is 1, and in the HashMap, the length of the map is always 2 n times, while 2 of the n-th-1 value of the binary is 1. So when we take the value of hashcode to calculate, if the hashcode bits number is less than or equal to length-1 bits number, then with the result is the value of Hashcode, if the former bit is greater than the number of digits, then with the calculation will be more out of the bit and 0 phase, The result is bound to be 0, which causes the value of the excess bit to be omitted, and the value under the body is the value of the hashcode%llength. As for why not use hashcode%length directly, because the bit operation is faster than the modulo operation.
Explained here should already clear this line of code meaning, here have to sigh, JDK author level is still high, the idea is not in how to implement, but how to achieve more efficient.