How do you specify the initial capacity of a hashmap when initializing it?

In Java, you can specify the initial capacity and load factor of a HashMap using its constructor. The parameters of the constructor are as follows:

HashMap(int initialCapacity, float loadFactor)

initialCapacity represents the initial capacity, which is the initial size of the HashMap, and loadFactor represents the load factor, indicating at what proportion of capacity the HashMap will perform a resizing operation.

For example, to initialize a HashMap with an initial capacity of 10, you can do it like this:

HashMap<String, Integer> map = new HashMap<>(10, 0.75f);

This initializes a HashMap with an initial capacity of 10 and a load factor of 0.75. When the number of elements in the HashMap reaches 7.5 (10 * 0.75), the HashMap will be resized.

Leave a Reply 0

Your email address will not be published. Required fields are marked *