gpt4 book ai didi

java - 如果所有元素都在同一个存储桶中,为什么会发生调整大小?

转载 作者:行者123 更新时间:2023-12-02 01:25:57 25 4
gpt4 key购买 nike

我编写了下面的代码来测试当所有元素都在同一个存储桶中结束时 HashMap 的行为:-

public class DerivedMain {

int data = 10;

@Override
public int hashCode() {
return data;
}

public static void main(String[] args) {

HashMap m = new HashMap();
for(int i=0;i<20;i++) {
m.put(i, i);
}

Field tableField = null;
try {
tableField = HashMap.class.getDeclaredField("table");
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tableField.setAccessible(true);
Object[] table = null;
try {
table = (Object[]) tableField.get(m);
} catch (IllegalArgumentException | IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table == null ? 0 : table.length);
}

}

我得到以下输出:-32

为什么即使所有元素都以同一个存储桶结尾,也会发生调整大小?

最佳答案

因为 HashMap 就是这样的作品:

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed.

HashMap 只知道,一旦达到限制,冲突的概率就会变得太高,它必须重新散列以降低该概率并为将来的条目留出空间。它假设 hashCode 的实现良好,并且绝对无法知道冲突是否是由于 hashCode 的糟糕实现而导致的运气不好。

关于java - 如果所有元素都在同一个存储桶中,为什么会发生调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929302/

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