HashSet in Java

Last Updated : 22 Nov, 2025

HashSet in Java implements the Set interface of the Collections Framework. It is used to store the unique elements, and it doesn't maintain any specific order of elements.

  • HashSet does not allow duplicate elements.
  • Uses HashMap internally which is an implementation of hash table data structure.
  • Also implements Serializable and Cloneable interfaces.
  • HashSet is not thread-safe. To make it thread-safe, synchronization is needed externally.
Java
import java.util.*;

class GFG 
{
    public static void main(String[] args) 
    {
        // Instantiate an object of HashSet
        HashSet<Integer> hs = new HashSet<>();

      	// Adding elements 
        hs.add(1);
        hs.add(2);
        hs.add(1);

        System.out.println("HashSet Size: " + hs.size());
        System.out.println("Elements in HashSet: " + hs);
    }
}

Output
HashSet Size: 2
Elements in HashSet: [1, 2]

Hierarchy Diagram of HashSet

It implements the Set interface, which is a sub-interface of the Collection interface.