HashMap通过哈希算法得出哈希值之后,将键值对放入哪个索引的方法
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
假设
HashMap的容量为16转化成二进制为10000,length-1得出的二进制为01111
哈希值为1111
可以得出索引的位置为15
假设
HashMap的容量为15转化成二进制为1111,length-1得出的二进制为1110
哈希值为1111和1110
那么两个索引的位置都是14,就会造成分布不均匀了,增加了碰撞的几率,减慢了查询的效率,造成空间的浪费。
总结:
- 因为2的幂-1都是11111结尾的,所以碰撞几率小。