Hashmap源码探索,如何确定数组的下标(二)

源代码

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值