java - HashMap中负载因子的意义是什么?

标签 java hashmap load-factor

HashMap 有两个重要的属性:大小负载因子。我浏览了 Java 文档,它说 0.75f 是初始负载因子。但我找不到它的实际用途。

有人可以描述一下我们需要设置负载因子的不同场景以及不同情况下的一些示例理想值是什么?

最佳答案

documentation解释得很好:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. 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 (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

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 - HashMap中负载因子的意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59528465/

相关文章:

data-structures - 关于负载因子的哈希表

java - 使用 cucumber-java 时如何组织步骤定义?

Java 或 Groovy : loop through hashmap and display html table in Velocity template

Java Hashmap 删除数据并替换为新数据

java - 通过使用超过 1 个深度级别的 map 从 csv 转换为 json

java - 如何根据android中的图像选择设置图像标题

java - 等待之后线程不应该处于阻塞状态而不是可运行状态吗?

java - 在 Java 上找不到符号错误?

java - 如何根据负载因子对 ConcurrentHashMap 中的元素进行分组

java - 如果 HashMap 的负载因子大于 1 会怎样?