简体   繁体   中英

Map load factor, how map grows

As per my understanding, and what I have read

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased

So, when loadfactor is .8(80%), with map size of 10, Map will grow by size 10, when 8 elements are put in Map .

So, now Map has size 20. My doubt is when next 10 element space will be added to Map .

  • when Map is again 80% full, that is when 16 elements are put in Map .

or

  • When 18 elements are put in Map .

Loadfactor of 80%, so 16 elements. It will calculate the resizing depending on the total amount of elements that are in there and the max capacity at that time.

It doesn't keep track of the last resizing.

That will be at 16. If you look at the java code for HashMap :

threshold = (int)(newCapacity * loadFactor);

where new capacity is the new size. Therefore the limit in your example will be 16.

A HashMap has a size() and a capacity , and these are two different things. Capacity is an internal size of a hash table and is always a power of two, so HashMap can't have capacity 20. Size is the number of hash entries which were put by user into this map.

When you declare a HashMap

Map map = new HashMap(20)

It's actual capacity is 32 and a threshold is 24. It's size is zero.

Map map = new HashMap()

For this case map has size 0 and the default capacity 16.

Threshold :

threshold = (int)(newCapacity * loadFactor) = 32 * 0.8 = 25;

Which is 25 for load factor 0.8. So as soon as your map reaches a size of 25 entries, it will be resized to capacity 64 containing same 25 entries.

Every time a resize of the map happens, threshold is recalculated as;

threshold = (int)(newCapacity * loadFactor);

So in your example, it will be 16.

Please refer the source of HashMap here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM