负哈希码的存储桶位置是什么?

问题描述 投票:1回答:1

如果我在hashcode方法中返回-1会发生什么?

否性哈希码的存储桶位置是什么?负哈希码将存储在地图条目的何处?

为什么不引起IndexOutOfBoundsException

java hashmap hashcode
1个回答
0
投票

我假设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]的数字。

© www.soinside.com 2019 - 2024. All rights reserved.