HashSet
HashSet is a set backed by a HashMap. It stores unique elements with average O(1) add, remove, and contains. Equality is equals, and there is no order.
Detailed Explanation
A set answers "have I seen this?" and "give me the unique items". HashSet implements that with a HashMap whose keys are the elements and whose values are a dummy object. Everything that is true of HashMap keys is true of HashSet elements: a correct equals/hashCode, no mutation after insert, unspecified iteration order, one null allowed.
add returns whether the set changed. contains is the lookup. remove deletes by equality, not by index. There is no get(i). Bulk operations addAll, retainAll, and removeAll implement union, intersection, and difference in place.
LinkedHashSet adds insertion order. TreeSet sorts. CopyOnWriteArraySet and ConcurrentHashMap.newKeySet() cover concurrent cases. Set.of and Set.copyOf create unmodifiable sets that reject nulls.
You reach for HashSet to deduplicate, to test membership in a large collection, and to implement visited sets in graph search. You keep a List when duplicates and order are the data. You do not use a set as a list: if you need the third element, you needed a list (or a LinkedHashSet plus an iterator, which is still the wrong tool for indexes).
The cost of a HashSet of boxed integers is higher than a sorted array plus binary search for a static set, and higher than a BitSet for dense small ints. The cost of a broken hashCode is linear contains. The cost of mutating an element after add is a ghost: contains returns false and add inserts a duplicate by equality that the set cannot find to remove.
Iteration is fail-fast: a structural change during an enhanced for throws ConcurrentModificationException. Remove through the iterator if you must delete while walking.
Code Examples
import java.util.HashSet;
import java.util.Set;
public class Unique {
public static void main(String[] args) {
Set<String> seen = new HashSet<>();
System.out.println(seen.add("ana")); // prints: true
System.out.println(seen.add("ana")); // prints: false
System.out.println(seen.contains("ana")); // prints: true
System.out.println(seen.size()); // prints: 1
}
}import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Dedup {
public static void main(String[] args) {
Set<Integer> ids = new HashSet<>(List.of(2, 1, 2, 3));
System.out.println(ids.contains(1)); // prints: true
System.out.println(ids.size()); // prints: 3
}
}Common Gotchas
Mutating an element after `add` breaks `contains`
the element sits in the old bucket. Use immutable elements.
Iteration order is unspecified
do not assert `[3, 1, 2]` vs `[1, 2, 3]` in tests.
`Set.of` rejects null and duplicates at creation
`HashSet` allows one null and silently ignores duplicate `add`.
`HashSet` is not thread-safe
use `ConcurrentHashMap.newKeySet()`.