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不同,也有可能映射到相同的位置上。
- HashMap里的hash、indexFor方法
- HashMap的indexFor方法
- Java HashMap的hash和indexFor函数
- HashMap中的indexFor方法分析
- HashMap里hash方法解读
- JDK之HashMap中的indexFor(int h, int length)方法
- HashMap 的 hash 方法原理
- 关于hashMap利用hashCode数组定位indexFor的理解
- indexFor方法分析
- HashMap解决hash冲突的方法
- 链表法HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决Hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- hashmap的hash方法出现原因
- 怎么使用jquery来突出加亮鼠标所停留在的表格行记录?
- 制度的重要性
- sql 多表连接查询(详细实例)
- VC++6.0注释快捷键设置
- 关于JS制作时钟的那些事儿
- HashMap里的hash、indexFor方法
- 数据结构——栈的动态实现(brk/sbrk)(Unix C语言实现)
- CentOS下MySQL修改密码、开启远程连接。
- UVA - 301 Transportation
- Oracle实例安装出现ORA-28000和ORA-00922错误
- TP-LINK WR720N 无线路由器 局域网内 设置上网 步骤
- HDOJ 5071 Chat 模拟
- oracle 细粒度审计使用
- C#实现的分数类