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

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.
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
| Constructor | Description |
|---|---|
| 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. |
| Method | Description | ||
|---|---|---|---|
| 1) | boolean | add(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. |
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());
}
}
}
Output:
Five One Four Two Three
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());
}
}
}
Output:
ADAM TOM PETERSON
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);
}
}
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: []
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());
}
}
}
Output:
Adam Tom Robert Emma
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);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications & Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6
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);
}
}
Output:
HashSet: [Robert, Andrew, Peter] Robert Andrew Peter Array: [Robert, Andrew, Peter] Custom Objects: [Emma 30, Jack 25]
We request you to subscribe our newsletter for upcoming updates.