HashMap 中的对象如何跨桶分布?

How are the objects distributed across buckets in a HashMap?

如果我在hashcode方法中return-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;
}

一个项目的'address'是:

tab[(n - 1) & hash]

其中 n 是桶的数量。这将始终导致 [0, n-1].

范围内的数字

根据评论区的澄清要求,让我解释一下&操作数的工作原理:

我们取 n = 10hash = -1

       n = 00001010
    hash = 11111111
n & hash = 00001010

& 是一个 bitwise and 运算符。这意味着,对于每一位,它都会检查它是否在两个参数中都打开。

由于 n 始终为非负数,因此在其 IEEE-754 表示中会有一些前导 0s

这意味着,& 操作的结果将至少有相同数量的前导零,因此小于或等于 n。