Set in Java

Master the Set interface in Java: uniqueness contract, HashSet vs TreeSet vs LinkedHashSet, equals/hashCode rules, and interview essentials.

Set<E> is a Collection that forbids duplicate elements. It models the mathematical concept of a set: each value appears at most once. The Set interface adds no methods beyond those in Collection, but it strengthens the contract of add: if the collection already contains an element e2 such that e.equals(e2), add(e) must return false and leave the set unchanged. This uniqueness guarantee makes Set the right tool for membership testing, deduplication, and set-algebra operations (union, intersection, difference).

The Set Contract

  • No two elements e1 and e2 in the set may satisfy e1.equals(e2).
  • At most one null element is allowed (permitted by HashSet, forbidden by TreeSet).
  • add(e) returns false (and does nothing) if the element is already present.
  • equals and hashCode on the elements must be consistent for HashSet and LinkedHashSet to work correctly.

Key Set Implementations

Implementation Ordering Null add/contains Thread-safe
HashSet None (hash table) One null O(1) average No
LinkedHashSet Insertion order One null O(1) average No
TreeSet Sorted (natural / Comparator) No O(log n) No
CopyOnWriteArraySet Insertion order Yes O(n) Yes (read-heavy)
ConcurrentSkipListSet Sorted No O(log n) Yes

Example 1: HashSet, LinkedHashSet, TreeSet

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetComparison {
    public static void main(String[] args) {
        // HashSet: no ordering guarantee
        Set<String> hash = new HashSet<>();
        hash.add("banana");
        hash.add("apple");
        hash.add("cherry");
        hash.add("apple"); // duplicate — ignored
        System.out.println("HashSet:       " + hash);       // order unpredictable

        // LinkedHashSet: preserves insertion order
        Set<String> linked = new LinkedHashSet<>();
        linked.add("banana");
        linked.add("apple");
        linked.add("cherry");
        linked.add("apple"); // duplicate — ignored
        System.out.println("LinkedHashSet: " + linked);     // [banana, apple, cherry]

        // TreeSet: sorted in natural order
        Set<String> tree = new TreeSet<>();
        tree.add("banana");
        tree.add("apple");
        tree.add("cherry");
        tree.add("apple"); // duplicate — ignored
        System.out.println("TreeSet:       " + tree);       // [apple, banana, cherry]
    }
}

Example 2: Set Operations (Union, Intersection, Difference)

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

public class SetOperations {
    public static void main(String[] args) {
        Set<Integer> a = new HashSet<>(Set.of(1, 2, 3, 4, 5));
        Set<Integer> b = new HashSet<>(Set.of(3, 4, 5, 6, 7));

        // Union: all elements from both sets
        Set<Integer> union = new HashSet<>(a);
        union.addAll(b);
        System.out.println("Union:        " + union);        // [1, 2, 3, 4, 5, 6, 7]

        // Intersection: only elements in both sets
        Set<Integer> intersection = new HashSet<>(a);
        intersection.retainAll(b);
        System.out.println("Intersection: " + intersection); // [3, 4, 5]

        // Difference: elements in a but not in b
        Set<Integer> difference = new HashSet<>(a);
        difference.removeAll(b);
        System.out.println("Difference:   " + difference);   // [1, 2]

        // Membership test — O(1) for HashSet
        System.out.println("Contains 3:   " + a.contains(3)); // true
        System.out.println("Contains 9:   " + a.contains(9)); // false
    }
}

The equals/hashCode Contract

HashSet and LinkedHashSet group elements by their hashCode bucket, then use equals to distinguish elements within the same bucket. For correct Set behaviour, objects stored in a hash-based set must honour this contract:

  • If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
  • If a.hashCode() == b.hashCode(), a.equals(b) may still be false (hash collision is allowed).
  • Once an object is stored in a HashSet, mutating the fields used in hashCode or equals corrupts the set — the object becomes unfindable.

TreeSet does not use hashCode at all; it relies solely on the natural order (Comparable) or the supplied Comparator. If the comparator returns 0 for two objects, TreeSet treats them as equal and stores only one, even if equals would return false.

Common Mistakes

  • Not overriding equals and hashCode together. If you override equals but not hashCode (or vice versa), two logically equal objects can end up in different buckets, making HashSet.contains return false for an object that is logically "already in" the set.
  • Mutating an object while it is stored in a HashSet. If you change fields that affect hashCode after adding an object to a HashSet, the object ends up in the wrong bucket. Subsequent contains and remove calls will not find it.
  • Using TreeSet with a Comparator inconsistent with equals. TreeSet considers two elements equal if the comparator returns 0, regardless of equals. This can silently lose elements if the comparator is not consistent with equals.
  • Using Set.of(...) and expecting mutable behaviour. Set.of(...) (Java 9+) returns an immutable set; any mutation throws UnsupportedOperationException. Use new HashSet<>(Set.of(...)) for a mutable copy.
  • Forgetting that TreeSet does not allow null. TreeSet cannot compare null with other elements and throws NullPointerException if you try to add null. HashSet allows exactly one null.

Best Practices

  • Choose HashSet by default when you only need uniqueness and fast membership testing.
  • Use LinkedHashSet when insertion order matters (e.g., deduplication while preserving encounter order).
  • Use TreeSet when you need a sorted unique sequence and can accept O(log n) operations.
  • Always override both equals and hashCode when using custom objects in a HashSet.
  • Prefer Set.of(...) for small, immutable sets; wrap in new HashSet<>() if mutability is needed.

Interview Questions

1. What is the Set interface in Java?

Set<E> is a Collection that does not allow duplicate elements. It strengthens the add contract: if the element is already present (by equals), add returns false and the set is unchanged. The three main implementations are HashSet (hash table, no order), LinkedHashSet (insertion order), and TreeSet (sorted order).

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

HashSet stores elements in a hash table with O(1) average add/contains and no ordering. LinkedHashSet adds a linked list to maintain insertion order, with the same O(1) performance but slightly higher memory use. TreeSet uses a red-black tree to keep elements sorted; add/contains are O(log n).

3. Why must you override both equals and hashCode for custom objects in a HashSet?

HashSet uses hashCode to locate the bucket and equals to check for duplicates within the bucket. If hashCode is not overridden, two logically equal objects may hash to different buckets and both be stored, violating the uniqueness contract. The general Java contract requires: a.equals(b) implies a.hashCode() == b.hashCode().

4. Can HashSet contain null?

Yes, exactly one null is allowed. HashSet handles null as a special case by placing it in a designated slot. TreeSet does not allow null because it cannot compare null to other elements, which would throw NullPointerException.

5. What happens if you mutate an object stored in a HashSet?

If you change fields used in hashCode after inserting the object, the set can no longer find it — contains(obj) returns false and remove(obj) fails. The object is effectively lost inside the set (occupying a bucket that is no longer searched). This is a common, hard-to-debug bug.

6. How do you perform set intersection and difference in Java?

Use retainAll for intersection: setA.retainAll(setB) keeps only elements in both sets. Use removeAll for difference: setA.removeAll(setB) removes all elements also in setB. Both methods mutate the receiver, so work on copies if you need the originals: new HashSet<>(setA).

7. What is the time complexity of TreeSet operations, and when is it preferred over HashSet?

TreeSet operations (add, remove, contains, first, last) are O(log n) because the underlying red-black tree maintains sorted order. Prefer TreeSet when you need sorted iteration, range queries (headSet, tailSet, subSet), or the NavigableSet API (floor, ceiling, higher, lower). HashSet is preferable when you only need fast membership tests without ordering.

Summary

  • Set<E> forbids duplicates and strengthens add to return false for already-present elements.
  • HashSet (O(1) average), LinkedHashSet (insertion order, O(1)), and TreeSet (sorted, O(log n)) cover most use cases.
  • equals and hashCode must be overridden together for custom objects in hash-based sets.
  • Mutating objects stored in a HashSet on fields used by hashCode corrupts the structure.
  • Set.of(...) returns an immutable set; wrap in new HashSet<>() for a mutable copy.

Continue Learning

Previous: PriorityQueue | Next: HashSet

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.