Java HashSet & LinkedHashSet: Hashing, Buckets and Uniqueness

HashSet is the premier implementation of the Set interface in Java. It models the mathematical set abstraction: it stores strictly unique elements, allows at most one null element, and provides near-instantaneous O(1) time complexity for add, remove, and contains operations.

How HashSet Works Internally (The Secret)

A common interview question asks how HashSet stores data without duplicates. The secret is that HashSet is internally backed by a HashMap:

// Inside JDK java.util.HashSet:
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object(); // Dummy value

public boolean add(E e) {
    // Adds element as KEY into internal HashMap!
    return map.put(e, PRESENT) == null;
}

Code Demonstration: HashSet & LinkedHashSet

import java.util.HashSet;
import java.util.LinkedHashSet;

public class SetDemo {
    public static void main(String[] args) {
        // 1. HashSet: Unordered unique collection
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("Java");
        hashSet.add("Python");
        hashSet.add("JavaScript");
        hashSet.add("Java"); // DUPLICATE: Silently ignored!

        System.out.println("HashSet (No order guaranteed): " + hashSet); // [Java, JavaScript, Python]
        System.out.println("Contains Python? " + hashSet.contains("Python")); // true (O(1))

        // 2. LinkedHashSet: Preserves exact insertion order
        LinkedHashSet<String> orderedSet = new LinkedHashSet<>();
        orderedSet.add("First");
        orderedSet.add("Second");
        orderedSet.add("Third");
        orderedSet.add("First"); // Duplicate rejected!

        System.out.println("LinkedHashSet (Preserves order): " + orderedSet); // [First, Second, Third]
    }
}

The Mandatory hashCode() and equals() Contract

The Golden Contract of Hashing

If you store custom objects (like Student or Employee) inside a HashSet or as keys in a HashMap, you MUST override both hashCode() and equals()! If obj1.equals(obj2) is true, then obj1.hashCode() MUST equal obj2.hashCode().

Next Step

When you need unique elements automatically sorted in ascending numerical or alphabetical order, use TreeSet. Proceed to: Java TreeSet & NavigableSet →

Frequently Asked Questions (FAQ)

Q1. How does HashSet guarantee uniqueness of elements in Java?
Internally, HashSet is backed by a HashMap! When you call hashSet.add(element), it puts the element as a KEY in the internal HashMap with a dummy Object as the value. Because HashMap keys must be strictly unique, duplicates are rejected automatically.
Q2. What is the difference between HashSet and LinkedHashSet?
HashSet does not guarantee any iteration order; order can change over time. LinkedHashSet maintains a doubly-linked list running across all its bucket entries, preserving the exact insertion order at the cost of slightly higher memory.
Q3. What happens if a custom class overrides equals() but fails to override hashCode() in a HashSet?
The contract is violated! Two logically equal objects will produce different hash codes and be placed into different buckets, allowing duplicate objects to exist inside the HashSet simultaneously!

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java TreeSet →

Sorted set alternative.

Java HashMap →

The underlying backing store of HashSet.

Java Iterators →

Iterating through sets.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!