为什么Map有loadFactor

为什么Map有loadFactor

本文介绍了为什么Map有loadFactor,List没有呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在Java中创建Map或List时,它们都具有相同的默认初始容量10.它们的容量随着获得新元素而增加。然而,列表仅在添加第11个元素时增长,并且当添加第8个元素时Map已经增长。它发生是因为Map有一个loadFactor字段,它调节如何饱和。当饱和度高于loadFactor时,Map会增长。默认情况下,loadFactor为0.75。



我不知道为什么列表和地图有不同的机制来决定何时增加初始容量?


c>有负载因子。当你降低负载系数时,你会获得更好的性能(但是你需要用更多的内存使用来支付)。



HashMap 例如。容量是背衬阵列的大小。但是,数组的每个位置可能包含多个条目。



另一方面,在 ArrayList 支持数组的每个索引保存单个元素,因此对于负载因子没有意义。


When one creates a Map or a List in Java, they both have the same default initial capacity of 10. Their capacity grows as they get new elements. However, the List only grows when the 11th element is added and the Map grows already when the 8th element is added. It happens because the Map has a loadFactor field, which regulates how "saturated" it can be. When the saturation is higher than the loadFactor, the Map grows. The loadFactor is 0.75 by default.

I wonder why do Lists and Maps have different mechanisms for deciding when to increase their initial capacity?

解决方案

Maps have load factor because the load factor determines their performance. When you lower the load factor, you get better performance (but you pay for it with increased memory usage).

Take HashMap for example. The capacity is the size of the backing array. However, each position of the array may contain multiple entries. The load factor controls how many entries in average would be stored in a single array position.

On the other hand, in ArrayList each index of the backing array holds a single element, so there's no meaning to a load factor.

这篇关于为什么Map有loadFactor,List没有呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:22