How to Create a HashSet With a Predefined Capacity in Java?
Last Updated :
01 Feb, 2024
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
import java.util.*;
class GFG {
public static void main (String[] args) {
int capacity = 10 ;
HashSet<String> myset = new HashSet<>(capacity);
myset.add( "Flowers" );
myset.add( "Fruits" );
myset.add( "Colours" );
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.
Share your thoughts in the comments
Please Login to comment...