You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Java HashMap桶定位逻辑的疑问:为何用(n-1)&hash而非hash%n?

关于Java HashMap putVal方法中下标计算的疑问

我正在研究Java HashMap类的putVal方法实现,参考代码如下:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

其中这段下标计算的代码让我产生疑问:

if ((p = tab[i = (n - 1) & hash]) == null)
    tab[i] = newNode(hash, key, value, null);

为何此处使用i = (n - 1) & hash来计算数组下标?按照我的理解,应该使用i = hash % n来获取数组中的位置,是不是我忽略了什么?


解答

  • 性能优先:位运算比取模快得多
    CPU对按位与运算&的支持是原生级别的,执行速度远快于取模运算%——取模本质是除法运算,需要更多CPU周期来完成。HashMap作为高频使用的集合类,每一次put操作都要计算下标,用位运算能显著提升整体性能。

  • 等价性的前提:HashMap数组长度是2的幂
    HashMap的数组长度n始终是2的幂(初始为16,每次扩容都翻倍,查看resize方法实现可确认)。当n是2的幂时,hash % n的结果和(n-1) & hash完全等价:
    比如n=16(二进制10000),n-1=15(二进制1111),此时hash & 15会保留hash值的低4位,这和hash % 16的结果完全一致。

  • 利用哈希扰动的成果
    HashMap计算hash值时,会对key的hashCode做一次扰动:hash = key.hashCode() ^ (hash >>> 16),目的是让hash值的高位也参与后续计算,减少哈希冲突。而(n-1) & hash刚好能利用到扰动后的所有有效位——当n较小时,hash的高位信息也能通过与运算影响最终下标,进一步降低冲突概率。

如果数组长度不是2的幂,(n-1) & hash和hash % n的结果就不相等了,所以HashMap才强制数组长度为2的幂,就是为了能用高效的位运算替代取模。


内容的提问来源于stack exchange,提问作者sanat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 15:56:03