Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When the initial capacity of the HashSet (i.e 16) gets filled up how is the new capacity is calculated? What is the formula?

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)

like image 610
Nilay Dhamecha Avatar asked Jun 24 '16 05:06

Nilay Dhamecha


People also ask

Why initial capacity of HashMap is 16?

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.

What is the initial capacity of HashSet?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

How do I set the size of a HashSet?

1) The number of items you can hold in your HashSet = initial capacity x load factor.

What are the initial capacity and load factor of HashSet choose at least one correct answer?

Default initial capacity of the HashMap takes is 16 and load factor is 0.75f (i.e 75% of current map size).


1 Answers

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.

like image 101
thegauravmahawar Avatar answered Nov 03 '22 10:11

thegauravmahawar