第二天,小粉粉和小灰灰又遇见了……
![](https://img.haomeiwen.com/i8244809/1bf6a564cad80b4f.png)
![](https://img.haomeiwen.com/i8244809/a94f2c5c56b81144.png)
![](https://img.haomeiwen.com/i8244809/09007ec16c7f794b.png)
![](https://img.haomeiwen.com/i8244809/f1efa16f65f60f75.png)
![](https://img.haomeiwen.com/i8244809/3a6b869c2d554a80.png)
![](https://img.haomeiwen.com/i8244809/8f599b4fd2e106b6.png)
之前咱们说过,有一个hash方法,用于计算元素的下标值。
index = hash(key)
在hash方法内部,我们通过key的hashCode值与HashMap的长度做某种运算,可以得到最后的index值。
![](https://img.haomeiwen.com/i8244809/9f896c5cf9ebdff2.png)
index = key.hashCode() % hashMap.length
![](https://img.haomeiwen.com/i8244809/5bbf8d9302412bc7.png)
1.对hash值进行调整
/**
* 如果Key值为null,返回0;如果Key值不为空,返回原hash值和原hash值无符号右移16位的值按位异或的结果。
* 按位异或就是把两个数按二进制,相同就取0,不同就取1。
* 所以这个hash()函数对于非null的hash值,仅在其大于等于2^16的时候才会重新调整其值。
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2.进行与运算
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// n的值是表长
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (n - 1) & hash,与hash值进行与元素
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//…………
我们知道 n-1 的二进制值是 1111,它与任何数进行与运算,结果都是那个数的最后四位(<=15)。
![](https://img.haomeiwen.com/i8244809/260708b4ec011265.png)
![](https://img.haomeiwen.com/i8244809/45a9b4cb90881322.png)
![](https://img.haomeiwen.com/i8244809/73ef9f3ad1676dc1.png)
![](https://img.haomeiwen.com/i8244809/1abfadae8033a871.png)
![](https://img.haomeiwen.com/i8244809/ed304a4733b9093d.png)
![](https://img.haomeiwen.com/i8244809/bad22c03dd88490c.png)
网友评论