定义 HashSet 的构造函数时
HashSet<Integer> hs = new HashSet<Integer>(10,(double)0.50);
第二个参数称为“填充比率”,默认值为 0.75。
我想知道将其默认为 0.75 是否有逻辑原因。
最佳答案
这个选择背后确实有逻辑推理。如果我们了解 HashSet
由 HashMap
支持,并认识到您帖子中的构造函数调用 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/