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/