gpt4 book ai didi

java - 防止 hashmap 调整为当前大小的两倍

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:00 25 4
gpt4 key购买 nike

我们有一个大小为一百万的 HashMap。我们必须存储 100 万和 100 个对象,但我们不希望 HashMap 增加到大小(200 万),这会使其当前大小(100 万)增加一倍,仅用于 100 个对象。

编辑:我想优化 hashmap 的大小调整。因为只存储 100 个对象,我们需要分配 100 万个对象的大小。所以这是浪费内存

我们如何克服这个问题?

最佳答案

HashMap 容量实现为 2 的幂,因此如果 2^20 (1048576) 对您来说不够,您将不得不使用 2^21 (2097152)。

编辑:

实际上,您可以通过指定高负载系数来控制容量。

如果准确的最大条目数为1000100,则当条目数达到容量*负载因子时,HashMap的容量将增加一倍。因此,如果容量为 1048576 并且您不希望它扩展到 2097152,则您需要大约 0.954 或更高的负载因子。

因此使用以下构造函数初始化实例应该可以解决问题:

 HashMap<String,Integer> map = new HashMap<> (1048576, 0.954);

相关代码(JDK 6):

public HashMap(int initialCapacity, float loadFactor) {
...
// Find a power of 2 >= initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;

this.loadFactor = loadFactor;
threshold = (int)(capacity * loadFactor);
table = new Entry[capacity];
...
}

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) // this is what you want to avoid
resize(2 * table.length);
}

关于java - 防止 hashmap 调整为当前大小的两倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31024014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com