【发布时间】:2020-07-03 14:59:40
【问题描述】:
如果我在 hashcode 方法中返回 -1 会发生什么?
负哈希码的存储桶位置是什么?映射的条目将存储在哪里用于负哈希码?
为什么它不会导致IndexOutOfBoundsException?
【问题讨论】:
-
@xenteros 嗨,非常感谢您的详细回答,但我仍在尝试了解如何为 -有哈希吗?
如果我在 hashcode 方法中返回 -1 会发生什么?
负哈希码的存储桶位置是什么?映射的条目将存储在哪里用于负哈希码?
为什么它不会导致IndexOutOfBoundsException?
【问题讨论】:
我假设 OP 了解 HashMap 的工作原理,问题只是关于技术细节。很多时候,人们解释跨桶分配值的过程只是简单地获取哈希的mod 来确定对象的桶索引。
当你有一个否定的hash:
(hash < 0 && n > 0 ) => hash % n < 0
要回答这个关于Java实现细节的问题,我们直接跳到源码:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
物品的“地址”是:
tab[(n - 1) & hash]
其中n 是存储桶的数量。这将始终导致[0, n-1] 范围内的数字。
根据评论部分的澄清要求,让我解释一下&操作数是如何工作的:
让我们以n = 10 和hash = -1 为例
n = 00001010
hash = 11111111
n & hash = 00001010
& 是 bitwise and 运算符。这意味着,对于每个位,它都会检查它是否在两个参数中都打开。
由于 n 始终为非负数,因此在其 IEEE-754 表示中会有一些前导 0s。
这意味着,& 操作的结果将具有至少相同数量的前导零,因此小于或等于 n。
【讨论】: