首页 > 求大神解读一下这段源码

求大神解读一下这段源码

java  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源码的一个函数,作用是将hashcode对应到hashmap数组里面的下标。`h & (length-1)`是什么运算呢?这样能保证下标是唯一的吗?

h & (length - 1) 等价于 h % length

& 是按位与,需要注意的是这里面 length 的值一定是 2 的幂

举例,length = 4 那么,(length - 1) 的二进制表示是 00000011,00000011 和任意数字进行 & 操作,等价于以 00000100 为除数的取余操作


这个方法非常巧妙,它通过 h & (table.length -1) 来得到该对象的保存位,而HashMap底层数组的长度总是 2 的 n 次方,这是HashMap在速度上的优化。在 HashMap 构造器中有如下代码:

见 一个非常巧妙的 hashcode 算法 return h & (length-1);

【热门文章】
【热门文章】