Skip to content

How to Create New HashSet in Java (HashSet Constructors)

This example shows how to create a new HashSet object in Java. This example also shows how to use various HashSet constructors that allow us to create new HashSet objects.

How to create new HashSet objects in Java using constructors?

The HashSet class in Java provides several constructors using which we can create new objects as given below.

How to create a new empty HashSet object?

The default HashSet constructor creates a new and empty HashSet object.

The HashSet object created using this constructor has the initial capacity of 16 (i.e. default capacity) and a load factor of 0.75.

If you want to specify the initial capacity while creating an object, you can use below given overloaded constructor that accepts the initial capacity argument.

The HashSet object created using this constructor has the specified initial capacity and default load factor i.e. 0.75.

If you want to specify both, the initial capacity and the load factor, you can use below given overloaded constructor.

The HashSet object created using this constructor has the specified initial capacity and load factor.

How to create a HashSet object from another collection object?

The HashSet class provides a constructor that accepts a Collection object as an argument.

This constructor creates a new HashSet object containing all elements of the specified collection object. The new set object has the default load factor i.e. 0.75 and initial capacity big enough to accommodate all the elements of the specified collection object.

The below given example shows how to create HashSet from an ArrayList object using this constructor.

Output

As you can see from the output, the element “1” was added only once in the HashSet as the HashSet class does not allow duplicate elements. You can also convert LinkedList to the HashSet in the same way.

This example is a part of the Java HashSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 HashSet

About the author

Leave a Reply

Your email address will not be published.