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
// 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:
- In the above example, we have initialized the capacity variable with 10 using the HashSet constructor.
- After that, we have passed as a parameter to the constructor HashSet for which myset has been created of size 10.
- Then it adds three elements by using add() method to the HashSet.
- At last, it prints the values of the HashSet.