HashMap里的hash、indexFor方法

来源:互联网 发布:王者荣耀网络检测出错 编辑:程序博客网 时间:2024/06/06 01:36

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
原创粉丝点击