HashMap里的hash、indexFor方法

hash和indexFor方法属于HashMap类,为什么jdk开发者需要使用另一种hash方法而不用键对象自己的hashcode方法,下面看一下hash和indexFor的源代码:

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

在hashcode值上再应用hash方法主要为了解决在低位上的冲突,借助一个例子来理解:

假设键对象的hashcode方法只返回三个值,31、63、95,它们都是int所以都是32位

31 = 0000 0000 0000 0000 0000 0000 0001 1111

63 = 0000 0000 0000 0000 0000 0000 0011 1111

95 = 0000 0000 0000 0000 0000 0000 0101 1111

hashMap的长度是16(2^4)

如果不使用hash方法:

indexFor将会返回

31 = 0000 0000 0000 0000 0000 0000 0001 1111 --> 1111 = 15

63 = 0000 0000 0000 0000 0000 0000 0011 1111 --> 1111 = 15

95 = 0000 0000 0000 0000 0000 0000 0101 1111 --> 1111 = 15

因为当调用indexFor方法,将会进行31&15、63&15、95&15的与操作

由于上面三个数最后四位都是1,indexFor后的值相同,虽然有不同的hashcode但是都会存在索引值为15的位置上

如果使用hash方法:

31 = 0000 0000 0000 0000 0000 0000 0001 1111 --> 0000 0000 0000 0000 0000 0000 0001 1110

63 = 0000 0000 0000 0000 0000 0000 0011 1111 --> 0000 0000 0000 0000 0000 0000 0011 1100

95 = 0000 0000 0000 0000 0000 0000 0101 1111 --> 0000 0000 0000 0000 0000 0000 0101 1010

使用新的hash值再调indexFor方法

0000 0000 0000 0000 0000 0000 0001 1110 --> 1110 = 14

0000 0000 0000 0000 0000 0000 0011 1100 --> 1100 = 12

0000 0000 0000 0000 0000 0000 0101 1010 --> 1010 = 10

使用了hash方法后被映射到了新的位置上

如果两个键对象有相同的hashcode,将会映射到相同的位置上。

如果两个键对象hashcode不同,也有可能映射到相同的位置上。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值