Attic
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

ClassOrderingInternal MechanismAverage LookupNull Element
HashSetNoneBacked by HashMap<E, Object>O(1)Allowed (Max 1)
LinkedHashSetInsertion OrderDoubly-linked hash bucketsO(1)Allowed (Max 1)
TreeSetSorted (Natural / Comparator)Red-Black Balanced TreeO(log n)Disallowed (Throws NPE)

Set Algebra in Java

Collection<E> provides bulk operations that execute standard mathematical set operations:

SetAlgebra.java
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]

Detailed Guides

On this page