Hashmap hash algorithm (conversion) and hashmaphash Algorithm
Hash table Locating Algorithm in HashMap:
int hash = hash(key.hashCode()); int i = indexFor(hash, table.length);
The source code of indexFor and hash is as follows:
/** * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because HashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ * in lower bits. Note: Null keys always map to hash 0, thus index 0. */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } /** * Returns index for hash code h. */ static int indexFor(int h, int length) { return h & (length-1); }
Now let's analyze the hash algorithm:
h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);
Assume that the value of key. hashCode () is 0x7FFFFFFF, and the value of table. length is 16 by default. The preceding algorithm is executed as follows:
I = 15, h ^ (h >>> 7) ^ (h >>> 4) in the result, replace h >>> 7 with h >>> 8. That is, after the last h ^ (h >>>> 8) ^ (h >>> 4) operation, the hashCode value is calculated as follows: 8 = 8 7 = 7 ^ 8 6 = 6 ^ 7 ^ 8 5 = 5 ^ 8 ^ 7 ^ 6 4 = 4 ^ 7 ^ 6 ^ 5 ^ 8 3 = 3 ^ 8 ^ 6 ^ 5 ^ 8 ^ 4 ^ 7 2 = 2 ^ 7 ^ 5 ^ 4 ^ 7 ^ 3 ^ 8 ^ 6 1 = 1 ^ 6 ^ 4 ^ 3 ^ 8 ^ 6 ^ 2 ^ 7 ^ 5 the first, second, and third digits in the result show repeated bits ^ calculation 3 = 3 ^ 8 ^ 6 ^ 5 ^ 8 ^ 4 ^ 7-> 3 ^ 6 ^ 5 ^ 4 ^ 7 2 = 2 ^ 7 ^ 5 ^ 4 ^ 7 ^ 3 ^ 8 ^ 6-> 2 ^ 5 ^ 4 ^ 3 ^ 8 ^ 6 1 = 1 ^ 6 ^ 4 ^ 3 ^ 8 ^ 6 ^ 2 ^ 7 ^ 5-> 1 ^ 4 ^ 3 ^ 8 ^ 2 ^ 7 ^ 5 (h> 7) instead of the (h> 8) algorithm, we should consider the occurrence of repeated bitwise ^ operations on the first, second, and third digits. So that all the 8 bits of the original hashCode on the hidden bit are involved in the ^ operation, so in the table. when length is 16 by default, any changes to the hashCode bit can basically be reflected in the final hash table location algorithm, in this case, only the 3rd-bit high 1-bit change of the original hashCode will not be reflected in the result, that is, I = 15 of 0x7FFFF7FF.