When the initial capacity of the HashSet (i.e 16) gets filled up how is the new capacity is calculated? What is the formula?
for example: as the size of array list increases by the formula New capacity = (current capacity * 3/2) + 1
and for vectors it is New capacity = (current capacity * 2)
The Initial Capacity is essentially the number of buckets in the HashMap which by default is 24 = 16. A good HashMap algorithm will distribute an equal number of elements to all the buckets. Say we have 16 elements then each bucket will have 1 node, the search for any element will be achieved with 1 lookup.
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
1) The number of items you can hold in your HashSet = initial capacity x load factor.
Default initial capacity of the HashMap takes is 16 and load factor is 0.75f (i.e 75% of current map size).
The HashSet
capacity is doubled
when the load factor (0.75)
is reached.
As the documentation explains:
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.
Example:
The initial capacity of HashSet
is 16
. When the load factor (0.75)
is reached, i.e. 16 * 0.75 = 12
; on the insertion of the 12th
element the capacity is doubled
, i.e. it becomes 32
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With