java - 在 HashMap 中,为什么阈值(调整大小的下一个大小值)是容量 * 负载因子。为什么不等于 map 的大小或容量

标签 java collections

在 HashMap 中,为什么阈值(调整大小的下一个大小值)是容量 * 负载 因子。为什么不等于大小 map 的容量

例如,初始默认容量 = 16,负载因子 = 0.75,因此 threshold = (capacity * load factor) = (16 * 0.75) = 12

当我们添加第 13 个元素时 map 调整大小为什么会这样,为什么 map 的作者决定保留它 capacity * load factor(即 12)?为什么与容量(即 16)不同。

为什么不保持阈值等于容量,以便仅在 hashmap 已满时才进行重新散列?

最佳答案

Javadoc,Javadoc,Javadoc。那是你首先看的地方。在 HashMap 上它说:

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.

根据 HashMap 的理论 - 如果您的映射已满,那么您正在做一些非常非常错误的事情。到那时,您可能会在 O(sqrt(N)) 上查找随机数据 - BAD。您从不希望您的 HashMap 已满。但是非常稀疏的 map 会浪费太多空间(正如您所指出的),并且迭代时间会太长。因此,应该有一个负载因子,在大多数用例中小于 1。

注意:“浪费的空间”与 map 大小成正比,与加载因子成反比。然而,查找时间具有更复杂的预期性能函数。这意味着相同的负载因子不适用于不同大小的 HashMap - 因为这将意味着不同的规模权衡。


可以在 Knuth“The Art of Computer Programming”第 3 卷中找到权衡的一般概述。

关于java - 在 HashMap 中,为什么阈值(调整大小的下一个大小值)是容量 * 负载因子。为什么不等于 map 的大小或容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384261/

相关文章:

java - 与 "nbsp"相关的 Xpath 错误

c# - 为什么 Collections.Generic.Queue 没有 Synchronized 方法而 Collections.Queue 有?

java - 客户端套接字接受的数据与服务器套接字不同

java - 从输入字符串中提取多项式系数

python - 如何在 Python 中创建一组集合?

java - 如何获得两个列表的笛卡尔积?

mongoDB 从具有关系的集合中选择

java - 迭代时从集合中删除元素

java - 使用 java.lang.Class 的实例创建参数化类的实例

java - 通过 Maven 使用 Informix 数据库