VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-create-a-hashset-with-a-predefined-capacity-in-java/

⇱ How to Create a HashSet With a Predefined Capacity in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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


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.
Comment