HashSet in Java

HashSet stores unique elements with O(1) average-case add, remove, and contains operations, backed internally by a HashMap.

HashSet<E> is the most commonly used Set implementation in Java. It guarantees that every element appears at most once, and it delivers O(1) average-case performance for add, remove, and contains. Internally it is backed by a HashMap where each element is stored as a key with a constant dummy value, so everything you know about HashMap applies here too.

How HashSet Works Internally

When you call add(e), HashSet calls e.hashCode(), spreads the hash across the backing array (default initial capacity 16), and stores the entry in the corresponding bucket. If two elements land in the same bucket (collision), they are stored in a linked list. From Java 8 onward, a bucket that grows beyond 8 entries is converted to a balanced red-black tree — but only when the total table capacity is at least 64; otherwise the table is resized first. The table resizes (doubles) when the number of entries exceeds capacity × loadFactor (default 0.75).

Operation Average Worst case (many collisions)
add O(1) O(log n) after treeification
remove O(1) O(log n)
contains O(1) O(log n)
Iteration O(n + capacity) O(n + capacity)

Key characteristics:

  • No duplicate elements.
  • null is permitted (at most one null).
  • Insertion order is not preserved.
  • Not thread-safe.

Examples

Basic usage

import java.util.HashSet;
import java.util.Set;

public class HashSetBasics {
    public static void main(String[] args) {
        Set<String> cities = new HashSet<>();
        cities.add("London");
        cities.add("Paris");
        cities.add("London");   // duplicate — silently ignored
        cities.add(null);

        System.out.println(cities.size());          // 3
        System.out.println(cities.contains("Paris")); // true
        cities.remove("Paris");
        System.out.println(cities.contains("Paris")); // false

        // Iteration order is not guaranteed
        for (String city : cities) {
            System.out.println(city);
        }
    }
}

Deduplication use case

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Deduplicate {
    public static void main(String[] args) {
        List<Integer> withDupes = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3);
        Set<Integer> unique = new HashSet<>(withDupes);
        System.out.println(unique); // e.g. [1, 2, 3, 4, 5, 6, 9] — order varies

        // Set operations
        Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
        Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 5, 6));

        Set<Integer> intersection = new HashSet<>(a);
        intersection.retainAll(b);
        System.out.println(intersection); // [3, 4]

        Set<Integer> union = new HashSet<>(a);
        union.addAll(b);
        System.out.println(union); // [1, 2, 3, 4, 5, 6]
    }
}

Common Mistakes

  1. Missing equals and hashCode on custom objects. If you store a custom class in a HashSet without overriding both methods, two logically equal objects will be treated as distinct entries because Object.equals uses reference equality. Always override both together, and ensure the contract holds: if a.equals(b) then a.hashCode() == b.hashCode().

  2. Mutating an element after insertion. If you change a field used in hashCode after the object is in the set, the element's bucket location becomes stale. Subsequent contains or remove calls may return wrong results. Use immutable objects as set elements wherever possible.

  3. Assuming iteration order. HashSet makes no iteration-order guarantee. Code that relies on a specific order will behave non-deterministically. Use LinkedHashSet for insertion-order or TreeSet for sorted order.

  4. Forgetting that null is allowed. Unlike TreeSet, a HashSet accepts a single null. Passing a null to TreeSet or using null with a natural-order Comparator throws NullPointerException.

  5. ConcurrentModificationException. Modifying a HashSet while iterating over it (outside of Iterator.remove()) throws ConcurrentModificationException. Use removeIf or collect elements to remove first, then call removeAll.

Best Practices

  • Declare variables using the Set<E> interface type so you can swap implementations without touching call sites.
  • Override both equals and hashCode together in custom key/element classes; use Objects.hash() for a clean implementation.
  • Pre-size the HashSet when the approximate element count is known: new HashSet<>(expectedSize, 0.75f) avoids rehashing.
  • Prefer contains over iterating to check membership — O(1) vs O(n).
  • Use Set.of(...) (Java 9+) for small, fixed sets where immutability is acceptable; it is also faster to create.

Interview Questions

1. What is HashSet and how is it implemented internally?

HashSet is a Set implementation that stores unique elements with O(1) average-case performance. Internally it delegates to a HashMap<E, Object>, using each element as the map key and a shared constant (PRESENT) as the value. Hash codes determine the bucket, collisions are handled with linked lists (converted to red-black trees at 8 entries per bucket once the table capacity is ≥ 64).

2. What is the difference between HashSet, LinkedHashSet, and TreeSet?

HashSet gives O(1) average operations with no ordering guarantee. LinkedHashSet maintains insertion order at a small memory cost. TreeSet keeps elements in sorted (natural or Comparator) order with O(log n) operations, backed by a red-black tree. Choose based on whether you need ordering and at what cost.

3. Why must you override both equals and hashCode?

The HashSet first compares hash codes (O(1) bucket lookup) and then uses equals to confirm identity within a bucket. If you override only equals, two equal objects may land in different buckets because their hash codes differ, so the set will store duplicates. The contract requires: a.equals(b) implies a.hashCode() == b.hashCode().

4. Can HashSet store null?

Yes. HashSet allows exactly one null element. It is placed in bucket 0 (since null has no hash code). TreeSet does not allow null because it calls compareTo (or Comparator.compare) on elements during insertion, which would throw NullPointerException.

5. When does HashSet resize, and what is treeification?

The backing HashMap resizes (doubles the array) when size > capacity × loadFactor (default 0.75). Treeification is the conversion of a linked-list bucket to a red-black tree when a single bucket accumulates more than 8 entries and the table capacity is at least 64; this caps worst-case lookup at O(log n) instead of O(n).

6. How do you safely remove elements during iteration?

Use Iterator.remove() — it removes the current element without triggering ConcurrentModificationException. Alternatively, use set.removeIf(predicate) (Java 8+) which is cleaner and handles the iterator internally.

7. What is a fail-fast iterator?

The iterators returned by HashSet (and most non-concurrent collections) are fail-fast: they track a modCount field on the backing map. If the set is structurally modified outside the iterator during iteration, the iterator throws ConcurrentModificationException on the next next() or remove() call. This is a best-effort safeguard, not a hard guarantee.

Summary

  • HashSet provides O(1) average-case add/remove/contains with no ordering guarantee.
  • It is backed by a HashMap; custom elements must correctly override equals and hashCode.
  • Buckets are treeified at 8 entries (table size ≥ 64) and the table resizes at 0.75 load factor.
  • Prefer LinkedHashSet for insertion order, TreeSet for sorted order.
  • Always modify via Iterator.remove() or removeIf to avoid ConcurrentModificationException.

Continue Learning

Previous: Set | Next: LinkedHashSet

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.