以下基于 JDK 8 中的 HashMap
进行分析,先看看这几个构造函数:
1 | /** |
可见,对于最常见的 new HashMap()
方法,仅仅将 loadFactor
设置为了默认的负载因子:0.75
,此时未对底层的数组 Node<K,V>[] table
进行初始化。
默认的负载因子为何要选择 0.75
呢?其中 HashMap 的 JavaDoc 中专门提到:
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.
If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.
我们看看 HashMap(int initialCapacity, float loadFactor)
方法中最后一行:this.threshold = tableSizeFor(initialCapacity)
,其中 tableSizeFor
方法实现如下:
1 | /** |