Java · Hash set · container
HashSet<E>
A set backed by a HashMap: constant-time add, contains and remove on average; one null allowed.
import java.util.HashSet; public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Java SE 25
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| add | O(1) | O(n) | Yes |
| contains | O(1) | O(n) | No |
| remove / removeIf | O(1) for remove | O(n) for removeIf (visits every element) | Yes |
| addAll / retainAll / removeAll | addAll O(m); retainAll O(n) contains calls on c; removeAll depends on which side is smaller | — | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- A HashMap<E, Object> whose values are a shared dummy object.
- Ordering
- None. LinkedHashSet keeps insertion order; TreeSet keeps elements sorted.
- Duplicates
- Not stored.
- Mutability
- Mutable; fail-fast iterators.
- Memory and ownership
- One HashMap node per element.
- Equality and comparison
- hashCode() then equals().
Pitfalls
- Set operations are the bulk methods addAll / retainAll / removeAll and they modify the receiver; copy first if you need the original.
- Changing a field used by hashCode() after adding an element makes it unfindable.
- Set.of(...) is immutable and rejects duplicates and null.
Alternatives
- LinkedHashSet (insertion order)
- TreeSet (sorted, O(log n))
- EnumSet (bit vector for enums)
- BitSet for small integers
In other languages
- C#: HashSet<T>
- Python: set
- C++: std::unordered_set<Key>