Open In App

How to Create a HashSet With a Predefined Capacity in Java?

In Java, we can create HashSet with a predefined capacity by creating a constructor and passing the capacity as a parameter to it. We have to initialize the capacity using a variable otherwise you can pass a direct value to it.

Syntax:

HashSet <datatype>myset=new HashSet<>(capacity);

Here, myset is the name of the set and capacity defines the size of it.

Program to Create a HashSet with a Predefined Capacity in Java




// Java Program to create a HashSet with a predefined capacity
import java.util.*;
  
class GFG {
    public static void main (String[] args) {
       
        int capacity = 10;
  
        // Create a HashSet with a predefined capacity
        HashSet<String> myset = new HashSet<>(capacity);
  
        // Adding elements to the HashSet
         
        myset.add("Flowers");
        myset.add("Fruits");
           myset.add("Colours");
  
        // Display the elements in the myset
        System.out.println(myset);
        
    }
}

Output
[Colours, Flowers, Fruits]

Explanation of the above Program:

Article Tags :