HashSet in Java
Learn how Java HashSet stores unique elements, how equals and hashCode define duplicates, and what to expect from membership costs and iteration.
Learn how Java HashSet stores unique elements, how equals and hashCode define duplicates, and what to expect from membership costs and iteration.
HashSet in Java
HashSet stores unique elements and is backed by a HashMap. Its basic membership operations are expected constant-time when hashes distribute elements properly; collisions add equality comparisons, and iteration also depends on backing-map capacity.
Introduction
Use HashSet when a collection should keep one copy of each equal element and you need frequent membership checks. equals() determines equality; hashCode() helps locate candidates. Equal elements must have equal hash codes, though unequal elements may share a hash and remain separate entries. The Java SE API’s constant-time statement assumes hashes distribute elements properly; collisions add equality comparisons.
Keep fields used by an element’s equals() and hashCode() stable while it is in the set. Changing them can make contains() or remove() miss the element. HashSet is unsynchronized, and its iteration order is unspecified; use LinkedHashSet when insertion order matters.
When to Use HashSet
Use HashSet when:
- You need to store a collection of unique elements
- You need expected constant-time membership checks when elements have well-distributed hash codes
- You do not need to store duplicates or maintain order
Do not use HashSet when:
- You need sorted elements (use
TreeSet) - You need insertion-order iteration (use
LinkedHashSet) - You need to maintain counts for duplicate elements (use
Map<E, Integer>orMultiset) - You need thread-safe unique collections (use
ConcurrentHashMap.newKeySet()orCollections.synchronizedSet())
Internal Structure
The Java SE API specifies that HashSet is backed by a HashMap. In OpenJDK, each element is stored as a map key and a shared dummy value is used for the mapping. That storage detail is an implementation choice:
// Simplified OpenJDK implementation sketch; not part of the public API
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
// add() calls map.put(element, PRESENT) — PRESENT is never used
public boolean add(E e) {
return map.put(e, PRESENT) == null; // null means key was absent (new element)
}
Mermaid Diagram: HashSet Internals
graph TD
A["HashSet<E>"] --> B["HashMap<E, Object>"]
B --> C["map.put(element, PRESENT)"]
C --> D["PRESENT = new Object()"]
D --> E["Used as dummy value for all entries"]
Failure Scenarios
| Scenario | Cause | Result |
|---|---|---|
ConcurrentModificationException |
A fail-fast iterator detects a structural edit outside that iterator | Best-effort diagnostic; not guaranteed or a correctness tool |
Duplicate add() returns |
An equal element is already present | Returns false; the set is unchanged |
Trade-Off Table
| Aspect | HashSet | TreeSet | LinkedHashSet |
|---|---|---|---|
| Ordering | None | Sorted (Red-Black tree) | Insertion order |
contains() / add() |
Expected constant time with well-distributed hashes | O(log n) | Expected constant time with well-distributed hashes |
| Memory overhead | Lowest | Tree node overhead | Linked list overhead |
null element |
One allowed | Not allowed | One allowed |
| Sorted operations | N/A | first(), last(), subSet() |
N/A |
Code Snippets
Basic Operations
add(), contains(), and remove() are the usual membership operations. add() returns true when it inserts a new element and false when an equal element is already present. These operations are expected constant-time when hashes distribute elements properly; collisions require more equals() comparisons. List.contains() instead scans elements one by one.
import java.util.HashSet;
import java.util.Set;
public class HashSetBasicsDemo {
public static void main(String[] args) {
Set<String> languages = new HashSet<>();
languages.add("Java");
languages.add("Python");
System.out.println("duplicate added = " + languages.add("Java"));
System.out.println("size = " + languages.size());
System.out.println("contains Java = " + languages.contains("Java"));
languages.remove("Python");
System.out.println("contains Python = " + languages.contains("Python"));
}
}
Save this as HashSetBasicsDemo.java, then run javac HashSetBasicsDemo.java && java HashSetBasicsDemo:
duplicate added = false
size = 2
contains Java = true
contains Python = false
Set Algebra Operations
retainAll() keeps the intersection, addAll() forms the union, and removeAll() removes the difference. Their cost depends on the collection sizes and the membership costs of the sets involved.
Set<String> a = Set.of("Java", "Python", "Go");
Set<String> b = Set.of("Python", "Rust", "Go");
Set<String> intersection = new HashSet<>(a);
intersection.retainAll(b); // ["Python", "Go"]
Set<String> union = new HashSet<>(a);
union.addAll(b); // ["Java", "Python", "Go", "Rust"]
Set<String> difference = new HashSet<>(a);
difference.removeAll(b); // ["Java"]
Converting Between List and Set
To deduplicate a list, pass it to the HashSet collection constructor. If an API needs a list back, wrap the set in new ArrayList<>(unique). The order is unspecified because HashSet makes no ordering promise. Use LinkedHashSet instead when insertion order matters; the conversion code stays the same.
List<String> withDuplicates = List.of("a", "b", "a", "c", "b");
// Deduplicate
Set<String> unique = new HashSet<>(withDuplicates);
// Convert back to a list; iteration order is unspecified
List<String> deduped = new ArrayList<>(unique);
Observability Checklist
- Monitor set size distributions — detect unbounded growth
- Profile
contains()in hot paths using representative element distributions - Profile hash function quality if set operations appear slow despite correct implementation
- Treat
ConcurrentModificationExceptionas a best-effort diagnostic, not a correctness mechanism - Use
Set.of()for small unmodifiable sets; it rejectsnullelements and duplicates
Security Notes
HashSetis unsynchronized; synchronize access when another thread may modify it, or use a concurrent set such asConcurrentHashMap.newKeySet()- Avoid storing sensitive elements (passwords, tokens) in sets that may be serialized or logged
- Consider
Collections.unmodifiableSet()when returning sets to external callers - When using custom objects as set elements, ensure
hashCode()andequals()are consistent and do not leak sensitive state
Common Pitfalls / Anti-Patterns
- Mutable elements as set members: If fields used by an element’s
equals()orhashCode()change while it is in the set,contains()andremove()may no longer find it - Confusing
add()return value:add()returnstrueif the element was added,falseif it was already present — this is not an error condition nullelement:HashSetallows onenull; adding it again returnsfalse. OtherSetimplementations may rejectnull.- Assuming set preserves insertion order: It does not; use
LinkedHashSetif order matters - Comparing membership costs:
List.contains()scans the list;HashSet.contains()is expected constant-time when hash codes distribute elements well. Collisions add equality comparisons.
Quick Recap
HashSetis backed byHashMap; the current OpenJDK implementation uses each element as a key and a shared dummy valueequals()defines duplicates; equal elements must also return equal hash codesadd(),contains(), andremove()are expected constant-time when hashes distribute elements properly- Iteration takes time proportional to the set size plus backing-map capacity
- No ordering guarantees; use
TreeSetfor sorted orLinkedHashSetfor insertion-order - Unsynchronized; synchronize access externally or use a concurrent set when needed
Interview Questions
Further Reading
- Java SE 27 HashSet API — Set behavior, expected operation costs, and iteration cost
- Java SE 27 Set API — Duplicate and equality semantics
- Java SE 27 HashMap API — Collision behavior and expected operation costs
- Baeldung: HashSet Internals — How HashSet uses HashMap internally and performance characteristics
- HashSet vs TreeSet vs LinkedHashSet — Comparison of Set implementations and when to use each
- Understanding HashSet Performance — Internal workings and time complexity analysis
- HashMap — HashMap collision behavior and key stability apply to HashSet elements too
- TreeMap and TreeSet — sorted set alternative using Red-Black trees
- Java Collections Utility — static utility methods for all collections
Conclusion
HashSet is a straightforward choice when a collection should reject equal elements. equals() determines whether elements are duplicates; matching hashCode() values help the set locate candidates. Membership operations are expected constant-time when hashes distribute elements well, while collisions add equality comparisons. Iteration also depends on the backing map’s capacity.
Keep fields used by an element’s equals() and hashCode() stable while it is in the set. If those values change, membership checks and removal may miss it. HashSet fits collections where equal elements should collapse to one entry and iteration order does not matter.
The HashMap article covers collision behavior and why key fields used by equals() and hashCode() should stay stable. For sorted unique elements, TreeSet offers O(log n) operations.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.