Open In App

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

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • The load value represents the ratio of the number of elements in the HashSet to the size of the hash table.
  • When the number of elements exceeds this ratio, the hash table will be updated to be useful.
  • The Default payload in Java’s HashSet is 0.75.
  • This is considered a good balance between space complexity and time complexity.

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




// 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:

  • The above Java program creates a HashSet with a custom initial capacity and load factor.
  • Then, it initializes the HashSet with a specific initial capacity and load factor.
  • After that it adds elements to the HashSet.
  • And then it prints the contents of the HashSet.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads