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

OperationTimeWorst caseChanges the collection
addO(1)O(n)Yes
containsO(1)O(n)No
remove / removeIfO(1) for removeO(n) for removeIf (visits every element)Yes
addAll / retainAll / removeAlladdAll 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

References