CKTIS / Java
util.HashSet: practical reference
util.HashSet: practical reference: HashSet<E> is a HashMap-backed set that retains one element by equals and hashCode, permits null, and defines no encounter order.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.HashSetHashSet is a HashMap-backed set that retains one element by equals and hashCode, permits null, and defines no encounter order.
Use it for fast membership tests and duplicate removal when result order is not part of the contract.
It is not synchronized, and mutating an element in a way that changes equals or hashCode after insertion can break contains and remove.
add, remove, and contains are constant-time on average with good hashing; iteration depends on size plus capacity, and fail-fast detection is only best effort.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var set = new java.util.HashSet<String>();
set.add("a");
set.add("a");
System.out.println(set.size());
}
}
Result
1
The example exercises the documented element in a small deterministic program and compares exact standard output.