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)`是什么运算呢?这样能保证下标是唯一的吗?
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 & (table.length -1) 来得到该对象的保存位,而HashMap底层数组的长度总是 2 的 n 次方,这是HashMap在速度上的优化。在 HashMap 构造器中有如下代码:
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
h & (length - 1) 等价于 h % length
& 是按位与,需要注意的是这里面 length 的值一定是 2 的幂
举例,length = 4 那么,(length - 1) 的二进制表示是 00000011,00000011 和任意数字进行 & 操作,等价于以 00000100 为除数的取余操作