Sitemap

HashSet in Java

2 min readMay 12, 2025

--

Press enter or click to view image in full size

A HashSet in Java is a part of the Java Collections Framework and is used to store a collection of unique elements. It is backed by a hash table (actually a HashMap instance), and it does not guarantee any specific order of its elements.

Key Features of HashSet:

  • No duplicates: It does not allow duplicate elements.
  • Null allowed: It allows the null element.
  • Unordered: The order of elements is not guaranteed.
  • Fast operations: Basic operations like add, remove, contains, and size have constant time complexity O(1) on average.
  • Not synchronised: It is not thread-safe by default.

Thread-safe means that a piece of code or a data structure can be safely used by multiple threads at the same time, without causing data corruption or unexpected behavior.

Get Saumya14’s stories in your inbox

Join Medium for free to get updates from this writer.

Thread: In Java (and many other languages), a thread is a separate path of execution. Multiple threads can run in parallel in a program.

Usage Example:

import java.util.HashSet;

public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet of Strings
HashSet<String> set = new HashSet<>();

// Add elements
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Apple"); // Duplicate, will not be added

// Check if an element exists
System.out.println(set.contains("Banana")); // true

// Remove an element
set.remove("Orange");

// Iterate over elements
for (String fruit : set) {
System.out.println(fruit);
}

// Size of the set
System.out.println("Set size: " + set.size());
}
}

Common Methods

  • add(E e): Adds the specified element if it is not already present.
  • remove(Object o): Removes the specified element if present.
  • contains(Object o): Returns true if the set contains the specified element.
  • size(): Returns the number of elements in the set.
  • clear(): Removes all elements from the set.
  • isEmpty(): Checks if the set is empty.

When to Use HashSet

  • When you need a collection of unique elements.
  • When you do not care about the order of elements.
  • When you need fast lookup, insertion, and deletion.

--

--