ReviseAlgo Logo

Collections Framework

HashSet

Analyze HashSet internal HashMap design, hashing distribution dependency, and constant lookup mechanisms.

Interview: Focuses on HashSet backing HashMap, PRESENT dummy object usage, O(1) performance limits, and null allowances.

Last Updated: June 13, 2026 10 min read

A HashSet is a hash table implementation of the Set interface. It is backed internally by a HashMap instance, using the Set's elements as keys.

HashMap Backing

Maps values directly to keys of an internal HashMap. The associated map value is a shared dummy object (PRESENT).

Constant Complexity

Provides O(1) constant time lookup, insertion, and deletion, assuming a well-distributed hash function.

Unordered Iteration

No iteration order guarantees. The order of elements changes when the backing HashMap is resized.

Backing HashMap implementation

The internal source code of HashSet reveals its structure:

public class HashSet<E> implements Set<E> {
    private transient HashMap<E, Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

public HashSet() { map = new HashMap<>(); } public boolean add(E e) { return map.put(e, PRESENT) == null; } }

Common Pitfalls

  • Assuming element sorting: Writing logic that assumes elements are retrieved in the order they were inserted, which breaks on resizing.
  • Missing hashCode override: Storing custom objects without overriding hashCode() and equals(), which allows duplicate objects to be stored.

Best Practices

  • Override hashCode and equals: Always implement both methods together on elements stored inside HashSet.
  • Pre-size backing maps: Provide initial capacities for sets to avoid resizing overhead on large datasets.

Interview-Relevant Information

Q1: How is HashSet implemented internally in Java?
Answer: HashSet is backed by an internal HashMap. Elements added to the HashSet are mapped as keys in the HashMap, and a dummy singleton object PRESENT is associated as the value for every key.

Q2: Does HashSet allow null elements?
Answer: Yes. It allows a single null element because the underlying HashMap supports a single null key.

Quick Checklist

Can you state the internal class backing HashSet, identify the dummy object value mapping, and explain why hashcode consistency is required? If yes, you understand HashSet.

Use Cases

Removing duplicate entities from data processing pipelines.

Fast presence checking (existence checks) in lookup tables.

Common Mistakes

Failing to override hashCode/equals in objects stored in a HashSet.

Iterating through a HashSet expecting sorted values.