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.

published: reading time: 12 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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> or Multiset)
  • You need thread-safe unique collections (use ConcurrentHashMap.newKeySet() or Collections.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 ConcurrentModificationException as a best-effort diagnostic, not a correctness mechanism
  • Use Set.of() for small unmodifiable sets; it rejects null elements and duplicates

Security Notes

  • HashSet is unsynchronized; synchronize access when another thread may modify it, or use a concurrent set such as ConcurrentHashMap.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() and equals() are consistent and do not leak sensitive state

Common Pitfalls / Anti-Patterns

  1. Mutable elements as set members: If fields used by an element’s equals() or hashCode() change while it is in the set, contains() and remove() may no longer find it
  2. Confusing add() return value: add() returns true if the element was added, false if it was already present — this is not an error condition
  3. null element: HashSet allows one null; adding it again returns false. Other Set implementations may reject null.
  4. Assuming set preserves insertion order: It does not; use LinkedHashSet if order matters
  5. 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

  • HashSet is backed by HashMap; the current OpenJDK implementation uses each element as a key and a shared dummy value
  • equals() defines duplicates; equal elements must also return equal hash codes
  • add(), contains(), and remove() 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 TreeSet for sorted or LinkedHashSet for insertion-order
  • Unsynchronized; synchronize access externally or use a concurrent set when needed

Interview Questions

1. How does HashSet decide whether an element is already present?
The `Set` contract treats two elements as duplicates when `equals()` says they are equal. A hash-based set uses `hashCode()` to locate candidates, so equal elements must also return equal hash codes. Unequal elements can share a hash code and still remain separate entries.
2. What is the time complexity of `HashSet.contains()`?
The Java SE API describes expected constant-time lookup when hash codes distribute elements properly. Collisions add `equals()` comparisons, so there is no unconditional constant-time guarantee for every input.
3. Can a HashSet contain null?
Yes. `HashSet` permits one `null` element. Adding `null` again returns `false` because that element is already present. Other `Set` implementations may reject `null`.
4. What is the relationship between `HashSet` and `HashMap`?
The Java SE API specifies that `HashSet` is backed by a `HashMap`. In the OpenJDK implementation, elements are map keys and a shared dummy value is used for each mapping. That representation is an implementation detail.
5. How much does iterating over a HashSet cost?
The Java SE API documents iteration cost as proportional to the set's size plus the capacity of its backing map. `HashSet` does not promise an iteration order; use `LinkedHashSet` when insertion order matters.
6. What does `HashSet.add()` return?
It returns `true` if the set changed because it accepted the element, and `false` if an equal element was already present. The API specifies this result; how the backing map detects the duplicate is an implementation detail.
7. Can different objects with the same hash code both be stored?
Yes. `hashCode()` helps locate candidates, while `equals()` determines whether an existing element is a duplicate. Unequal objects can share a hash code and both belong to the set. Heavy collisions increase comparison work; see the [HashMap article](/blog/technical/java-hashmap/) for collision details.
8. What are the default capacity and load factor?
The Java SE 27 API documents a default initial capacity of 16 and a load factor of 0.75 for the default constructor. Growth and allocation details belong to the implementation, not the `Set` contract. For a known approximate size, use the capacity-taking constructor to reduce resizing.
9. How do I create a set that callers cannot modify?
Use `Set.of("a", "b", "c")` for a small unmodifiable set. `Collections.unmodifiableSet(existingSet)` returns an unmodifiable view of an existing set; changes through another reference to that set are still visible through the view.
10. How does HashSet differ from LinkedHashSet?
`HashSet` makes no iteration-order promise. `LinkedHashSet` preserves insertion order and uses more memory for its linked structure. Both provide expected constant-time basic operations when hashes distribute elements properly.
11. Why does HashSet reject duplicate elements?
A set cannot contain two elements that are equal according to its equality rules. For `HashSet`, implement `equals()` and `hashCode()` consistently: if two objects are equal, they must have the same hash code. Unequal objects may have the same hash code.
12. How does HashSet differ from IdentityHashMap?
`HashSet` follows equality semantics based on `equals()`. `IdentityHashMap` is a separate map implementation that compares keys by reference identity (`==`) instead. It is useful only when object identity is the intended key rule.
13. What if an element's hash code changes after insertion?
If a field used by `equals()` or `hashCode()` changes while the object is in the set, `contains()` and `remove()` may no longer find it. Keep those fields stable while the object is stored. The [HashMap article](/blog/technical/java-hashmap/) explains the same key-stability issue for map keys.
14. How does `HashSet.contains()` compare with `List.contains()`?
`List.contains()` checks elements in sequence, so its work grows with list size. `HashSet.contains()` is expected constant-time when hashes distribute elements well; collisions increase equality comparisons. Choose based on ordering, duplicate, and access needs.
15. Can HashSet evict old elements to stay within a size limit?
No. `HashSet` has no eviction policy. For a small custom cache, `LinkedHashMap` can support eviction through `removeEldestEntry()`; for production caching, choose a cache implementation with the eviction policy you need.
16. What happens when I add the same element twice?
The first call can return `true`; the second call returns `false` if the element is still equal to the stored element. No exception is thrown, and the set still contains one such element.
17. What does `HashSet.clear()` do?
It removes all elements, leaving the set empty. The public API does not promise whether the implementation retains or reallocates its internal storage.
18. Is `HashSet.of()` a way to create a fixed set?
There is no `HashSet.of()` method. Use `Set.of("a", "b", "c")` to create an unmodifiable set, or `new HashSet<>(...)` when you need a mutable set.
19. Do hash codes alone determine whether two HashSet elements are duplicates?
No. Equal hash codes only identify candidates for comparison. `equals()` determines whether two elements are duplicates; distinct elements with colliding hash codes can both be stored. Equal objects must return equal hash codes.
20. What does LinkedHashSet add compared with HashSet?
`LinkedHashSet` maintains insertion-order iteration, while `HashSet` leaves order unspecified. The linked structure uses extra memory. Its basic operations, like those of `HashSet`, have expected constant-time performance when hashes distribute elements properly.

Further Reading

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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals