当达到HashMap或HashSet最大容量时会发生什么?

hu山

几分钟前,我回答了一个问题,询问“ Java中HashMap的最大可能大小 ”。正如我一直阅读的那样,HashMap是一个可扩展的数据结构。它的大小仅受JVM内存大小的限制。因此,我认为它的大小没有硬性限制,因此做出了相应的回答。(同样适用于HashSet。)

但有人纠正我说,既然大小() HashMap中的方法返回一个INT,还有就是它的大小有限制。完全正确的一点。我只是尝试在本地测试它,但失败了,我需要8GB以上的内存才能在HashMap中插入超过2147483483647个整数,而我没有。

我的问题是:

  • 当我们尝试在HashMap / HashSet中插入2,147,483,647 + 1个元素时会发生什么?
  • 是否抛出错误?
  • 如果是,哪个错误?如果不是,那么HashMap / HashSet,它已经存在的元素和新元素会发生什么?

如果有人可以访问拥有16GB内存的计算机,那么您可以实际尝试一下。:)

彼得·劳瑞:

阵列的基础容量必须为2的幂(限制为2 ^ 30)。达到此大小时,有效地忽略了负载因子,并且阵列停止增长。

此时,冲突率增加。

由于hashCode()仅具有32位,因此无论如何都不能将其增大得太大。

/**
 * Rehashes the contents of this map into a new array with a
 * larger capacity.  This method is called automatically when the
 * number of keys in this map reaches its threshold.
 *
 * If current capacity is MAXIMUM_CAPACITY, this method does not
 * resize the map, but sets threshold to Integer.MAX_VALUE.
 * This has the effect of preventing future calls.
 *
 * @param newCapacity the new capacity, MUST be a power of two;
 *        must be greater than current capacity unless current
 *        capacity is MAXIMUM_CAPACITY (in which case value
 *        is irrelevant).
 */
void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

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

当大小超过Integer.MAX_VALUE时,它将溢出。

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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章