HashMap面试系列(1)
Q:HashMap中的Hash码如何计算?为什么要这么做?
注意:HashCode()是对象的Hash码,和HashMap中的Hash码不是同一个东西
1.8版本如下
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
关于位运算
&:两个1是1,其余为0
|:1个1是1,其余为0
^: 同0,异1
h是对象的hashcode,h右移16位也就是取最高位的16位(一共32位)。
与原来的hashcode进行异或运算(同0异1)。
由此可知又移16位和HashCode的^运算,不对hashCode()的高16位进行改变:1&0=1
那么这样做的意义何在???
目的:减少hash碰撞
在jvm虚拟机中,一个hashcode位32,那么右移16位进行打乱的^操作,即是对低16位一次打乱,而且混合后的低位掺杂了高位的部分特征,使高位的信息也被保留下来
1.7版本如下
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);
}
功能和1.8版相似