# How HashSet Works Internally

> How does HashSet ensure uniqueness internally? What happens if you mutate an object after adding it to a HashSet?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-hashset-internals
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

How does HashSet ensure uniqueness internally? What happens if you mutate an object after adding it to a HashSet?

## Answer

The neat thing about HashSet is that it is barely a class of its own. Once you know HashMap, you already know HashSet, and an interviewer asking about it is really testing whether you can connect the dots.

Internally, a HashSet holds a private HashMap. When you create a HashSet, it creates a HashMap behind the scenes. Every element you add to the set becomes a key of that map, and the value is a shared dummy constant object named PRESENT, a static final Object. So set.add(e) is essentially map.put(e, PRESENT) == null. The put method returns the previous value for the key; if the key was new, the previous value is null, which means the add succeeded and the method returns true. If the key already existed, put returns PRESENT (non-null), so add returns false and the set is unchanged. That is the whole uniqueness mechanism.

Since keys of a HashMap are unique according to hashCode and equals, the set inherits that behaviour. The element's hashCode finds the bucket, and equals decides whether an equal element is already there. So if you store your own objects in a HashSet without overriding equals and hashCode, two logically identical objects will both be stored, because they use identity semantics by default.

Other operations follow directly: contains delegates to map.containsKey, remove to map.remove, size to map.size. Everything is O(1) on average, and the treeification and resizing rules are exactly those of HashMap. The default capacity is 16 and the load factor 0.75. The constructor HashSet(Collection c) sizes the map to max(c.size() / 0.75 + 1, 16) to avoid early resizes.

Iteration order is unpredictable and may change after a resize. If you need insertion order, use LinkedHashSet, which is backed by LinkedHashMap. If you need sorted order, use TreeSet, backed by a TreeMap, which uses compareTo or a comparator for uniqueness instead of equals.

Now the trap question: what if you mutate an object after adding it? Suppose the object's hashCode depends on a field, and you change that field while the object is inside the set. The element is still sitting in its old bucket, but its new hash points elsewhere. Now contains and remove compute the new hash, look in the wrong bucket, and fail to find it. The element becomes unreachable through the set API while still occupying memory: a logical memory leak. The same danger applies to HashMap keys, and it is the reason immutable keys such as String, Integer and records are ideal.

Two more facts. HashSet permits one null element, since HashMap permits one null key. And HashSet is not thread-safe; for concurrent use, use ConcurrentHashMap.newKeySet() or Collections.synchronizedSet.

If asked how to remove duplicates from a list quickly, the answer is new LinkedHashSet<>(list) when order matters, or new HashSet<>(list) when it does not.

## Code examples

### add() return value and the mutable element trap

```
import java.util.*;

public class HashSetDemo {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        System.out.println(set.add("x"));
        System.out.println(set.add("x"));

        List<String> item = new ArrayList<>(List.of("a"));
        Set<List<String>> holder = new HashSet<>();
        holder.add(item);
        item.add("b");
        System.out.println(holder.contains(item));
        System.out.println(holder.size());

        List<Integer> nums = List.of(4, 2, 4, 9, 2);
        System.out.println(new LinkedHashSet<>(nums));
    }
}
```

add returns false for a duplicate. Mutating the list changes its hashCode, so contains looks in the wrong bucket and returns false even though the set still holds the object. LinkedHashSet removes duplicates while keeping order.

## Key points

- HashSet is a wrapper over HashMap; elements are keys and the value is a dummy PRESENT object.
- add returns false when the element already exists.
- Uniqueness relies on hashCode and equals of the element.
- Mutating an element after insertion can make it unreachable.
- LinkedHashSet keeps insertion order; TreeSet keeps sorted order.

## Common follow-up questions

- How does TreeSet detect duplicates?
- What is the time complexity of HashSet operations?
- How can you remove duplicates from a list while preserving order?
- Is HashSet thread-safe?

## Interview tips

- State the sentence: HashSet stores elements as keys of an internal HashMap. That single line answers most follow-ups.
- Bring up the mutable element trap yourself; it shows you have seen real bugs.

## Concepts covered

HashSet, HashMap, Uniqueness, Mutable Keys, LinkedHashSet

Previous: [HashMap vs Hashtable vs ConcurrentHashMap](https://www.internhack.in/learn/interview/java-interview/java-hashmap-hashtable-concurrenthashmap) · Next: [Comparable vs Comparator and How TreeMap Sorts](https://www.internhack.in/learn/interview/java-interview/java-comparable-comparator-treemap) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe)
- [Generics, Wildcards and Type Erasure](https://www.internhack.in/learn/interview/java-interview/java-generics-type-erasure)
- [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model)
- [Garbage Collection Basics and GC Roots](https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics)
- [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable)
- [synchronized vs volatile: Visibility, Atomicity and Ordering](https://www.internhack.in/learn/interview/java-interview/java-synchronized-volatile)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
