如果我在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。