hashmap的hash算法( 转)

# HashMap 中hash table 定位算法：

`int hash = hash(key.hashCode()); int i = indexFor(hash, table.length);`

```/** * 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);
} ```

`h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);`

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

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

2022-12-15 14:39

2022-12-14 16:03

01-09 20:37

2022-12-20 22:24

2022-12-28 21:41

2022-12-29 12:27
Durham University_2022

2022-12-23 00:18

2022-12-18 21:46

01-06 21:26

2022-12-28 14:56

2022-12-07 16:56

2022-12-26 19:44

2022-12-30 15:34

02-03 16:32