源代码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
位扰动--->充分利用数组的空间,避免产生hash碰撞,所谓的hash碰撞就是同一index出现了相同的值,因此用链表解决
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
重点:(n - 1) & hash]
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
明白两个概念:
异或运算:
与运算:
位移运算:
实例:
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<>();
map.put("杨过","小龙女");
System.out.println("hashCode "+ "杨过".hashCode());
int index = Math.abs("杨过".hashCode() % 16);
System.out.println(index);
System.out.println("位干扰hash: "+ hash("杨过".hashCode()));
System.out.println("位干扰index "+ hash("杨过".hashCode())%15);
}
逻辑过程:
不足32位的,左边补0,
h = "杨过".hashCode:0000 0000 0000 1101 0001 0101 0101 1111
往右移动16位,超出32位,高位补0,超出部分删掉,溢出
h>>>16:0000 0000 0000 0000 0000 0000 0000 1101
异或运算:相同得0,不同得1
hash值:h ^ (h>>>16):0000 0000 0000 1101 0001 0100 0101 0010
15的二进制位:0000 0000 0000 0000 0000 0000 0000 1111
最终的index为:
与运算:oo得0,11得1,10得0
//高位补0
index=(16-1) & hash:0000 0000 0000 0000 0000 0000 0000 0010 =2