HashMap实现原理:容量、负载因子、hash与定位都搞定了吗?( 四 )



hashCode方法

注意key.hashCode()的多态用法 。 重点是hash方法 。

hash方法的实现和定位

前面已经说过 , 在get和put计算下标时 , 先对hashCode进行hash操作 , 然后再通过hash值进一步计算下标 , 如下图所示:

回顾hash方法的源码可知 , hash方法大概的作用就是:高16bit不变 , 低16bit和高16bit做了一个异或 。

javadoc这样说:

Computes key.hashCode() and spreads (XORs) higher bits of hash to lower. Because the table uses power-of-two masking sets of hashes that vary only in bits above the current mask will always collide. (Among known examples are sets of Float keys holding consecutive whole numbers in small tables.) So we apply a transform that spreads the impact of higher bits downward. There is a tradeoff between speed utility and quality of bit-spreading. Because many common sets of hashes are already reasonably distributed (so don’t benefit from spreading) and because we use trees to handle large sets of collisions in bins we just XOR some shifted bits in the cheapest possible way to reduce systematic lossage as well as to incorporate impact of the highest bits that would otherwise never be used in index calculations because of table bounds.

推荐阅读