java.util · java.base · since Java 1.2
HashSet
public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, SerializableHash-table set (a HashMap with dummy values): O(1) add/contains/remove, arbitrary iteration order. The default Set.
- Iteration order is unspecified and changes — never assert on it
- Elements need consistent equals/hashCode and must not mutate while inside
Key methods
HashSet(int initialCapacity) | Presize the backing table (default load factor 0.75f) to skip rehashes during bulk loads. |
HashSet(int initialCapacity, float loadFactor) | Presize with an explicit load factor. |
static <E> HashSet<E> newHashSet(int numElements) | Correctly presized factory — computes capacity from the expected element count, unlike the raw constructor (Java 19+). |