Open In App

How to Create a HashSet with a Custom Initial Load Factor in Java?

Java HashSet is a simple data structure provided by the Java Collection Framework that provides efficient storage and enables the storage of unique objects. One of the parameters that affect its performance is the load factor, which determines when the underlying hash table should be updated to accommodate multiple items.

In this article, we will learn how to create a HashSet with a Custom Initial Load Factor in Java.



Load Factor

Before moving to the implementation, let us understand the concept of load factors.

Syntax:

HashSet<E> hashSet = new HashSet<E>(int initialCapacity, float loadFactor);

Program to create a HashSet with Custom Load Factor in Java

To create a HashSet with a custom initial value in Java, we use the constructor of the HashSet class. This allows the initial capacity and load factor to be determined.






// Java program to create a HashSet with a custom initial load factor 
import java.util.*;
public class Main{
  public static void main(String args[]){
    // custom initial capacity
        int initialCapacity = 16;
          
        // custom load factor
        float customLoadFactor = 0.75f;
          
        // create HashSet with custom initial capacity and load factor
        HashSet<String> customHashSet = new HashSet<>(initialCapacity, customLoadFactor);
          
        // add elements to the HashSet
        customHashSet.add("Element 1");
        customHashSet.add("Element 2");
        customHashSet.add("Element 3");
          
        // print the HashSet
        System.out.println("Custom HashSet: " + customHashSet);
    }
}

Output
Custom HashSet: [Element 1, Element 3, Element 2]

Explanation of the Above Program:

Article Tags :