CollectionsSets
Overview
Unique element collections, comparison trade-offs, and mathematical set algebra
A Set<E> represents a collection that contains no duplicate elements. Java provides three core set implementations that vary in ordering guarantees and time complexity.
Set Hierarchy & Characteristics
| Class | Ordering | Internal Mechanism | Average Lookup | Null Element |
|---|---|---|---|---|
HashSet | None | Backed by HashMap<E, Object> | O(1) | Allowed (Max 1) |
LinkedHashSet | Insertion Order | Doubly-linked hash buckets | O(1) | Allowed (Max 1) |
TreeSet | Sorted (Natural / Comparator) | Red-Black Balanced Tree | O(log n) | Disallowed (Throws NPE) |
Set Algebra in Java
Collection<E> provides bulk operations that execute standard mathematical set operations:
Set<Integer> a = new HashSet<>(Set.of(1, 2, 3));
Set<Integer> b = new HashSet<>(Set.of(2, 3, 4));
// 1. Union (A ∪ B)
Set<Integer> union = new HashSet<>(a);
union.addAll(b); // [1, 2, 3, 4]
// 2. Intersection (A ∩ B)
Set<Integer> intersection = new HashSet<>(a);
intersection.retainAll(b); // [2, 3]
// 3. Difference (A \ B)
Set<Integer> difference = new HashSet<>(a);
difference.removeAll(b); // [1]