HashMap最大容量为什么是2的32次方

本文深入探讨了HashMap的容量限制及扩容机制,详细介绍了其默认初始容量、最大容量、负载因子等核心参数,并通过源码分析展示了HashMap如何在达到特定阈值时进行扩容,以及在达到最大容量时的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//默认的桶数组大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//极限值(超过这个值就将threshold修改为Integer.MAX_VALUE(此时桶大小已经是2的31次方了),表明不进行扩容了)
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子(请阅读下面体会这个值的用处)
static final float DEFAULT_LOAD_FACTOR = 0.75f;

观察jdk中HashMap的源码,我们知道极限值为2的31次方。

    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;//将threshold置为Integer.MAX_VALUE
            return;//当HashMap的容量已经是2的31次方的时候,直接返回。
        }

        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable);
        table = newTable;
        threshold = (int)(newCapacity * loadFactor);
    }

观察jdk中源码可发现当HashMap的容量已经是2的31次方的时候,就不会在进行扩容了。

    /**
         * The next size value at which to resize (capacity * load factor).
     * @serial
     */
    int threshold;

如上为对threshold的定义。

    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }

观察如上源码可知,当添加完元素后的容量大于threshold,就调用resize方法。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值