AKh*_*AKh 5 java algorithm hash hashmap data-structures
我浏览了 HashMap 的源代码并有几个问题。PUT 方法采用 Key 和 Value 并执行
使用上一步获得的哈希计算该对的存储桶位置
public V put(K key, V value) {
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
.....
}
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
static int indexFor(int h, int length) {
return h & (length-1);
}
Run Code Online (Sandbox Code Playgroud)例子:
问题:
预先感谢阿克
对于你的第一个问题:地图总是使用 2 的幂作为大小(如果你给它的容量为 10,它实际上会使用 16),这意味着它index & (length - 1)总是在范围内[0, length),所以它总是在范围内。
目前尚不清楚你的第二个问题和第三个问题与什么有关。我认为 HashMap除非需要,否则不会重新分配一切。