HashSet: Unique Collections

HashSet: Unique Collections in Java: A large construction site controls access with a turnstile at the gate.

The Analogy: The Induction Turnstile At A Site Gate

A large construction site controls access with a turnstile at the gate. Every worker who has completed the safety induction has a card, and when they arrive they swipe it. The turnstile keeps a register of which cards belong to inducted workers, and the swipe answers exactly one question: is this card in the register? It answers instantly, because the reader jumps straight to the slot the card number hashes to rather than reading down a paper list of hundreds of names. The register does not record when you arrived or how many times you have swiped -- only whether your card is known.

The register holds each card once. Swipe an already-inducted card and the gate simply confirms you are known; it does not create a second entry, and the register does not grow. That is the whole nature of the thing: it is a collection of distinct cards, and adding a card that is already present is a no-op that reports "already there". Asking how many workers are inducted is asking how many distinct cards the register holds.

What counts as "the same card" is decided entirely by the printed card number the reader keys on. Reissue a worker a fresh plastic card carrying the same number and the register treats it as the identical entry. When two different card numbers happen to hash to the same slot, the gate groups them there and compares the full numbers to tell them apart, so no two workers are ever confused as long as their numbers differ. The register's correctness rests on that one rule: the thing it keys on must genuinely identify the worker.

The failure mode: a contractor reconfigures the gate to identify workers by surname instead of card number, thinking names are friendlier on the report. Now two different workers who both happen to be called Smith collapse into a single register entry. The first Smith inducts and swipes in. The second Smith -- a different man who never sat the induction -- swipes, the gate finds "Smith" already in the register, and waves him onto the scaffold as though he were already cleared. The set did its job perfectly; it was told the wrong thing about what makes two workers the same.


Syntax or Core Structure

import java.util.HashSet;
import java.util.Locale;
import java.util.TreeSet;

public class SiteGate {
    public static void main(String[] args) {
        HashSet<Integer> inducted = new HashSet<>();

        System.out.println("first:    " + inducted.add(4471));
        System.out.println("again:    " + inducted.add(4471));
        System.out.println("second:   " + inducted.add(2290));
        inducted.add(3812);
        inducted.add(1005);

        System.out.println("has 2290: " + inducted.contains(2290));
        System.out.println("has 9999: " + inducted.contains(9999));

        inducted.remove(3812);
        System.out.println("size:     " + inducted.size());

        System.out.println("--- register ---");
        for (int card : new TreeSet<>(inducted)) {
            System.out.println(
                String.format(Locale.ROOT, "card %04d", card));
        }
    }
}

Output:

first:    true
again:    false
second:   true
has 2290: true
has 9999: false
size:     3
--- register ---
card 1005
card 2290
card 4471

The second add(4471) returns false and leaves the register unchanged. The iteration runs through a TreeSet purely to make the printed order deterministic -- a plain HashSet has no order to rely on.


Technical Depth: How A Set Is Really A Map, Why Element Identity Is Everything, And What Ordering You Do And Do Not Get

HashSet Is A HashMap In Disguise

A HashSet holds no machinery of its own for storage. Internally it wraps a HashMap where the set's elements are the map's keys and every value is the same shared placeholder object, a constant named PRESENT. Calling set.add(x) calls map.put(x, PRESENT) and returns true only if the key was new; set.contains(x) calls map.containsKey(x); set.remove(x) calls map.remove(x). Everything you learned about HashMap buckets, the power-of-two table, chaining, treeification, load factor, and rehashing applies unchanged, because it is literally the same code. A HashSet is a HashMap with the values thrown away. See [[hashmap]] for the bucket mechanics this rests on.

Element Identity: The Same equals And hashCode Contract

Because elements are keys, what makes two elements "the same element" is decided by hashCode and equals, exactly as with map keys. Every set operation routes through that pair.

OperationUses hashCode toUses equals to
addpick the bucketreject an equal element already present
containspick the bucketconfirm a match in the chain
removepick the bucketfind the element to unlink
retainAllprobe the other setdecide membership

If a class overrides equals without hashCode, equal elements scatter across buckets and the set will happily hold two elements it considers equal, because they never meet in the same bucket to be compared. That defeats the one guarantee a set exists to provide.

add Returns Whether The Set Changed

Every mutating method reports whether the set actually changed, and idiomatic code reads that boolean rather than checking membership first.

import java.util.HashSet;
import java.util.List;

public class Changed {
    public static void main(String[] args) {
        HashSet<String> tools = new HashSet<>();

        System.out.println("add A:    " + tools.add("auger"));
        System.out.println("add A2:   " + tools.add("auger"));
        System.out.println("rm A:     " + tools.remove("auger"));
        System.out.println("rm A2:    " + tools.remove("auger"));
        System.out.println("addAll:   "
            + tools.addAll(List.of("saw", "drill", "saw")));
        System.out.println("size:     " + tools.size());
    }
}

Output:

add A:    true
add A2:   false
rm A:     true
rm A2:    false
addAll:   true
size:     2

The second add and the second remove return false because the set did not change. addAll returns true if even one element was new, and the duplicate "saw" inside its argument is silently collapsed, leaving size 2.

Set Algebra Through Bulk Operations

The bulk methods turn a set into an algebra. addAll is union, retainAll is intersection, and removeAll is difference. Each mutates the receiver in place, so you copy first if you need the original.

import java.util.HashSet;
import java.util.TreeSet;

public class Shifts {
    public static void main(String[] args) {
        HashSet<Integer> morning =
            new HashSet<>(java.util.List.of(1005, 2290, 4471));
        HashSet<Integer> afternoon =
            new HashSet<>(java.util.List.of(2290, 4471, 7788));

        HashSet<Integer> union = new HashSet<>(morning);
        union.addAll(afternoon);

        HashSet<Integer> both = new HashSet<>(morning);
        both.retainAll(afternoon);

        HashSet<Integer> only = new HashSet<>(morning);
        only.removeAll(afternoon);

        System.out.println("union: " + new TreeSet<>(union));
        System.out.println("both:  " + new TreeSet<>(both));
        System.out.println("only:  " + new TreeSet<>(only));
    }
}

Output:

union: [1005, 2290, 4471, 7788]
both:  [2290, 4471]
only:  [1005]

The Ordering You Do And Do Not Get

Like its backing map, a HashSet promises nothing about iteration order, and that order shifts across resizes and JVM versions. Two sibling implementations trade a little cost for a guarantee.

ImplementationIteration orderNull elementCost of add/contains
HashSetNone (bucket layout)One allowedO(1) average
LinkedHashSetInsertion orderOne allowedO(1) average, slightly more memory
TreeSetSorted (natural or comparator)Not allowedO(log n)

Reach for LinkedHashSet the moment you need deduplication that still iterates in the order elements arrived, and TreeSet when you need the elements sorted or need range queries. Never let a test assert on HashSet iteration order.

Mutable Elements Are The Same Trap As Mutable Keys

Because elements are keys, mutating a field that participates in hashCode after adding an element strands it in the wrong bucket, exactly as with a map key. The element is still in the set by iteration but contains cannot find it, and you can add a second element the set now considers distinct, breaking uniqueness. The defence is identical: use immutable elements, or elements whose hash-relevant fields never change once added.


Real World Example: A Site Register That Deduplicated Workers By Surname

The gate software tracks who is inducted in a HashSet<Worker>. The Worker class was written to compare by surname -- the author reasoned that the report reads better with names than numbers, and made equals and hashCode key on the surname string. The card number is stored but ignored for identity. The result is that two different workers who share a surname are, to the set, the same worker.

import java.util.HashSet;
import java.util.Locale;

public class Induction {

    static final class Worker {
        final int card;
        final String surname;

        Worker(int card, String surname) {
            this.card = card;
            this.surname = surname;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Worker w
                && w.surname.equals(surname);
        }

        @Override
        public int hashCode() {
            return surname.hashCode();
        }
    }

    static String swipe(HashSet<Worker> reg, Worker w) {
        boolean added = reg.add(w);
        return String.format(Locale.ROOT,
            "card %04d %-8s %s",
            w.card, w.surname, added ? "ADDED" : "WAVED");
    }

    public static void main(String[] args) {
        HashSet<Worker> register = new HashSet<>();

        System.out.println(swipe(register, new Worker(4471, "Smith")));
        System.out.println(swipe(register, new Worker(2290, "Okafor")));
        System.out.println(swipe(register, new Worker(3812, "Smith")));
        System.out.println("size:     " + register.size());
    }
}

Output:

card 4471 Smith    ADDED
card 2290 Okafor   ADDED
card 3812 Smith    WAVED
size:     2

Three different workers swiped, but the register holds two. The third swipe, card 3812, was a man the site had never inducted, yet the gate found "Smith" already present, add returned false, and the software read that false as "already cleared" and let him through. The set behaved exactly as specified: it rejected an element it considered equal to one already held. The defect is entirely in what Worker declared equality to mean.

The fix is to key identity on the card number, the one field that genuinely identifies a worker, and to leave it final. With equals and hashCode computed from card, all three swipes add distinct entries and the register reads three, because 4471, 2290, and 3812 are three different numbers regardless of surname. Surname can still ride along in the report; it just has no business deciding who is the same person.

There is a deeper lesson than "pick the right field". A HashSet cannot validate its own notion of identity -- it trusts equals and hashCode completely, and if they encode a business rule that is subtly wrong, the set enforces that wrong rule flawlessly and silently. Nothing throws, nothing logs; a man simply walks onto a scaffold. Uniqueness is only ever as correct as the equality you hand the set.

The genuine limit worth naming is that this class of bug is invisible to the type system and usually invisible in testing, because a test fixture rarely contains two distinct objects that collide under the flawed rule. The design flaw is treating a human-friendly display field as an identity field; identity should key on something guaranteed unique and immutable -- here, the card number issued once and never reused. A quieter flaw: HashSet permits one null element, so a stray add(null) would sit in the register undetected until some later code dereferenced it.


Common Mistakes

  1. Overriding equals without hashCode. Equal elements scatter across buckets and the set holds duplicates it believes are distinct, defeating the sole guarantee a set provides. Override both, over the same fields.
  1. Keying identity on a display field. Surnames, names, and labels are not unique. Key equals and hashCode on a genuinely unique, stable field, and let display fields ride along without deciding identity.
  1. Mutating an element after adding it. Changing a hash-relevant field strands the element in the wrong bucket, so contains misses it and a "duplicate" can be added. Use immutable elements.
  1. Reading add's boolean as "the element exists". add returns whether the set changed, which is the opposite: true means it was new. Do not invert the meaning when gating on it.
  1. Asserting on HashSet iteration order. The order reflects bucket layout and changes across resizes and JVM versions. Use LinkedHashSet for insertion order or TreeSet for sorted order when order matters.
  1. Expecting bulk operations to leave the receiver untouched. addAll, retainAll, and removeAll mutate the set they are called on. Copy the set first when you need the original preserved.
  1. Using a HashSet where counts matter. A set records presence, not multiplicity, so adding the same element twice changes nothing. Use a Map<E, Integer> or a multiset when you need counts.
  1. Removing from a set while iterating it directly. Structural modification during a for-each throws ConcurrentModificationException. Use the iterator's own remove, or collect then removeAll.
  1. Sizing initial capacity to the exact element count. A HashSet resizes at capacity times load factor just as HashMap does, so capacity 100 still resizes at 75. Pass expectedSize / 0.75 + 1.

Best Practices

  • Key equals and hashCode on a unique, immutable field. Identity should rest on something guaranteed distinct and never reassigned, not on a human-friendly label.
  • Use immutable elements. Records, strings, boxed primitives, and enums cannot mutate underneath the set; a custom class should mark every hash-relevant field final.
  • Read add's return value for "did this change the set". It is the idiomatic way to detect first-time insertion in one bucket probe rather than a contains-then-add pair.
  • Pick the implementation by ordering need. HashSet for plain deduplication, LinkedHashSet to preserve insertion order, TreeSet for sorted iteration or range queries.
  • Use the bulk operations for set algebra. addAll, retainAll, and removeAll express union, intersection, and difference clearly; copy first to keep an operand intact.
  • Presize when the count is known. An initial capacity of expectedSize / 0.75 + 1 removes interim resizes, matching the HashMap it wraps.
  • Reach for ConcurrentHashMap.newKeySet() for a concurrent set. A plain HashSet is not thread-safe; the concurrent key-set view gives lock-free reads and safe writes.
  • Remove during iteration through the iterator. iterator.remove is the only safe in-loop removal; a direct set.remove inside a for-each throws.

Practice Exercises

  1. The Two Smiths. Write a Worker class with a card and a surname, first keying equals and hashCode on surname. Add three workers where two share a surname and print the set size, observing the missing worker. Then re-key identity on card, mark it final, and show all three now register, explaining why the card number is the correct identity field.
  1. Union, Intersection, Difference. Given two HashSet<Integer> of shift rosters, compute the union, intersection, and difference into three new sets without mutating either roster, printing each through a TreeSet for deterministic order. Then explain which method maps to each set operation and why copying the receiver first is necessary.
  1. Dedup That Keeps Order. Given a list of card numbers with duplicates, produce the distinct cards in first-seen order. Do it with a HashSet and observe that iteration order is not the arrival order, then switch to a LinkedHashSet and confirm the order is preserved, explaining what LinkedHashSet adds to justify the difference.