HashSet in Java

HashSet in Java is a class, Which implements the Set interface in Java.


Set In Java 

A Set is a collection that contains unique records only. The set can’t contain the Duplicate Records. In provides three general purpose implementations in Java.

  • HashSet
  • LinkedSet
  • TreeSet


HashSet in Java

The HashSet class is the simplest implementation of the Set interface. The HashSet does not add any additional methods beyond those found in the Set interface. The HashSet achieves good performance by using a hash to store the Object in the Set. The hash allows fast lookup. Any Object placed in a HashSet must implement the hashCode( ) and equals( ) methods. We will discuss more of this in a little while.


HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don’t care about insertion order.


The HashSet offers “constant time” performance. This means the performance of basic functions such as add, remove, etc is based on two factors which can be specified in the constructor of the HashSet, initial capacity and load factor.


Values of HashSet is — [Matt, null, Anshul, John, Eden, Mirilla]


In the above example, First we have declared the HashSet, and then add some elements in the HashSet.

Have you noticed we add duplicate values as well but in output we are getting only unique values. One more thing the values stored in the HashSet is not in the order they inserted.

We have seen, How we can declare and implement the HashSet in Java.


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply