Java HashSet

Last Updated : 8 Oct 2026

In Java, a HashSet class is a part of the Collections Framework that uses a hashing mechanism to store elements uniquely, whereas it does not maintain insertion order and focuses on fast search and retrieval operations.

In this chapter, we will learn about the Java HashSet class, its features, internal working using hashing, and how it differs from other collection types like List.

What is Java HashSet?

Java HashSet class is used to create a collection that uses a hash table for storage.  It inherits the AbstractSet class and implements the Set interface.

HashSet stores elements based on their hash codes, which allows fast operations such as insertion, deletion, and searching.

The important points about the Java HashSet class are:

  • It stores the elements by using a mechanism called 
  • It contains unique elements only.
  • It allows a null value.
  • HashSet class is non-synchronized. If we need a synchronized (thread-safe) version of HashSet, we can use the synchronizedSet() method to wrap the HashSet with a synchronized set.
  • It does not maintain the insertion order. Here, elements are inserted on the basis of their hashcode. If we need to maintain the insertion order, we can use a LinkedHashSet, which is another implementation of the Set interface that keeps the insertion order of its elements.
  • It is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Hierarchy of HashSet Class

The HashSet class extends the AbstractSet class and implements the Set interface, which further inherits from the Collection and Iterable interfaces. In simple terms, the hierarchy follows this order: Iterable → Collection → Set → AbstractSet → HashSet.

Internally, it uses a HashMap where each element is stored as a key. It uses the hash code of elements to store and retrieve data efficiently, which makes operations like add, remove, and search very fast.

Java HashSet class hierarchy

Another important point is that HashSet does not maintain insertion order, so elements may appear in random order. If we need to maintain order, we can use LinkedHashSet. Also, if a duplicate element is added, it is ignored, and the add() method returns false.

HashSet Class Declaration

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

HashSet Class Constructors

ConstructorDescription
HashSet()It is used to construct a default HashSet.
HashSet(int capacity)It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
HashSet(int capacity, float loadFactor)It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
HashSet(Collection<? extends E> c)It is used to initialize the hash set by using the elements of the collection c.

HashSet Class Methods

MethodDescription
1)booleanadd(E e)It is used to add the specified element to this set if it is not already present.
clear()It is used to remove all of the elements from the set.
clone()It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
contains(Object o)It is used to return true if this set contains the specified element.
isEmpty()It is used to return true if this set contains no elements.
iterator()It is used to return an iterator over the elements in this set.
remove(Object o)It is used to remove the specified element from this set if it is present.
size()It is used to return the number of elements in the set.
spliterator()It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

Example: Implementing HashSet

Java

import java.util.*;    
public class Main {    
 public static void main(String args[]){    
  //Creating HashSet and adding elements    
    HashSet<String> set=new HashSet();    
           set.add("One");      
           set.add("Two");      
           set.add("Three");     
           set.add("Four");    
           set.add("Five");    
           Iterator<String> i=set.iterator();    
           while(i.hasNext())    
           {    
           System.out.println(i.next());    
           }    
 }    
}   
Compile and Run

Output:

Five
One
Four
Two
Three

Example: Ignoring Duplicate Elements

HashSet does not allow duplicate elements. If a duplicate value is added, it is ignored. In this example, we see that HashSet does not allow duplicate elements.

Java

import java.util.*;    
public class Main {    
 public static void main(String args[]) {    
  //Creating HashSet and adding elements    
  HashSet<String> set=new HashSet<String>();    
  set.add("ADAM");    
  set.add("TOM");    
  set.add("PETERSON");    
  set.add("TOM");    
  //Traversing elements    
  Iterator<String> itr=set.iterator();    
  while(itr.hasNext()) {    
   System.out.println(itr.next());    
  }    
 }    
}  
Compile and Run

Output:

ADAM
TOM
PETERSON

Example: Removing Elements from HashSet

We can remove elements from a HashSet using methods like remove(), removeAll(), removeIf(), and clear(). The following example demonstrates different ways to remove elements from a HashSet.

Java

import java.util.*;    
public class Main {    
 public static void main(String args[]) {    
  HashSet<String> set=new HashSet<String>();    
           set.add("Oliver");    
           set.add("Emma");    
           set.add("Smith");    
           set.add("James");    
           System.out.println("An initial list of elements: "+set);    
           //Removing specific element from HashSet    
           set.remove("Smith");    
           System.out.println("After invoking remove(object) method: "+set);    
           HashSet<String> set1=new HashSet<String>();    
           set1.add("Methew");    
           set1.add("Peter");    
           set.addAll(set1);    
           System.out.println("Updated List: "+set);    
           //Removing all the new elements from HashSet    
           set.removeAll(set1);    
           System.out.println("After invoking removeAll() method: "+set);    
           //Removing elements on the basis of specified condition    
           set.removeIf(str->str.contains("Emma"));      
           System.out.println("After invoking removeIf() method: "+set);    
           //Removing all the elements available in the set    
           set.clear();    
           System.out.println("After invoking clear() method: "+set);    
 }    
}    
Compile and Run

Output:

An initial list of elements: [James, Oliver, Smith, Emma]
After invoking remove(object) method: [James, Oliver, Emma]
Updated List: [James, Methew, Oliver, Peter, Emma]
After invoking removeAll() method: [James, Oliver, Emma]
After invoking removeIf() method: [James, Oliver]
After invoking clear() method: []

Example: Creating HashSet from Another Collection

We can create a HashSet using another collection like ArrayList. The following example demonstrates how to create a HashSet from an existing collection.

Java

import java.util.*;    
public class Main  {    
 public static void main(String args[]) {    
   ArrayList<String> list=new ArrayList<String>();    
           list.add("Tom");    
           list.add("Adam");    
           list.add("Robert");         
           HashSet<String> set=new HashSet(list);    
           set.add("Emma");    
           Iterator<String> i=set.iterator();    
           while(i.hasNext())    
           {    
           System.out.println(i.next());    
           }    
 }    
}  
Compile and Run

Output:

Adam
Tom
Robert
Emma

Example: Using HashSet with Custom Object

We can store custom objects in a HashSet and traverse them like normal elements. The following example demonstrates how to store and display custom objects in a HashSet.

Java

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
	this.id = id;
	this.name = name;
	this.author = author;
	this.publisher = publisher;
	this.quantity = quantity;
}
}
public class Main {
public static void main(String[] args) {
	HashSet<Book> set=new HashSet<Book>();
	//Creating Books
	Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
	Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
	Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
	//Adding Books to HashSet
	set.add(b1);
	set.add(b2);
	set.add(b3);
	//Traversing HashSet
	for(Book b:set){
	System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
	}
}
}
Compile and Run

Output:

101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Example: Different Functionalities of HashSet

The following example demonstrates multiple features like iteration, conversion, and storing custom objects.

Java

import java.util.*;    
class Person {    
 private String name;    
 private int age;     
 public Person(String name, int age) {    
  this.name = name;    
  this.age = age;    
 }    
 public int hashCode() {    
  return name.hashCode() + age;    
 }    
 public boolean equals(Object o) {    
  if (this == o) return true;    
  if (!(o instanceof Person)) return false;    
  Person p = (Person)o;    
  return age == p.age && name.equals(p.name);    
 }    
 public String toString() {    
  return name + " " + age;    
 }    
}    
public class Main {    
 public static void main(String[] args) {    
  HashSet<String> set = new HashSet<String>();    
set.add("Robert");    
  set.add("Peter");    
  set.add("Andrew");    
  System.out.println("HashSet: " + set);    
  Iterator<String> it = set.iterator();    
  while(it.hasNext()){    
    System.out.print(it.next()+" ");    
  }    
  String[] arr = set.toArray(new String[0]);    
  System.out.println("\nArray: "+Arrays.toString(arr));    
  HashSet<Person> pset = new HashSet<Person>();    
  pset.add(new Person("Emma",30));    
  pset.add(new Person("Jack",25));    
  System.out.println("Custom Objects: "+pset);    
 }    
}    
Compile and Run

Output:

HashSet: [Robert, Andrew, Peter]
Robert Andrew Peter 
Array: [Robert, Andrew, Peter]
Custom Objects: [Emma 30, Jack 25]