java - 为什么HashSet构造函数的默认填充比例是0.75?

标签 java hashset

定义 HashSet 的构造函数时

HashSet<Integer> hs = new HashSet<Integer>(10,(double)0.50);

第二个参数称为“填充比率”,默认值为 0.75。

我想知道将其默认为 0.75 是否有逻辑原因。

最佳答案

这个选择背后确实有逻辑推理。如果我们了解 HashSetHashMap 支持,并认识到您帖子中的构造函数调用 HashMap 构造函数:

public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}

然后继续相关的HashMap documentation我们可以看到重要选择背后的逻辑推理。

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

关于java - 为什么HashSet构造函数的默认填充比例是0.75?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631877/

相关文章:

java - PowerMock 和 Mockito 似乎无法尽快模拟静态字段

c# - 为什么在 Contains 期间不调用 GetHashCode?

java - int 值的验证

java - GWT + GAE/J,通过线路发送 JDO 对象,但是如何呢?

java - 在java中使用格式化程序进行左对齐和右对齐-无法弄清楚如何正确格式化

java - 从 HashSet 中删除元素

java - 如何将两个HashSet分别添加到有序TreeSet中

java - 正确使用 HashSet.contains()?

Java HashSet 与数组性能

java - 在我的应用程序中获取 java.lang.ClassCastException