Scrivio Interview library
InternalsFoundations6 min read · updated 12 November 2026

How is java.util.HashSet implemented, and how does add() report whether the element was new?

java.util.HashSet is a thin wrapper around a HashMap<E, Object>: each element is stored as a key, and every key maps to the same shared dummy value called PRESENT. add(e) calls map.put(e, PRESENT) and returns true when put returned null, which means the key was not there before. So everything about HashMap applies to HashSet, including hashing, buckets, tree bins, resizing and the load factor, and elements need correct equals and hashCode and must not change while in the set.

Why this question is asked

HashSet is one of the most used collections in Java, and knowing that it is built on HashMap explains almost every question about it: why add is fast, why mutable elements get lost, why it allows one null and why it is not thread-safe. Interviewers ask this to see whether we understand collections as layers built on each other rather than as separate black boxes. In this answer, we will recap what a set promises, look at how HashSet delegates to HashMap, follow add() to see how it reports a new element, and then go through the HashMap rules that HashSet inherits, with code showing the classic lost-element bug.

1A Quick Recap of What a Set Promises

A Set is a collection with no duplicate elements, where duplicate means equal according to equals. Its core operations are add, remove and contains. For HashSet, all three are expected O(1): the time does not grow with the number of elements, as long as the elements' hash codes spread well.

Achieving that needs exactly what HashMap already has: a way to find a key quickly by its hash, and a guarantee that each key appears only once. So rather than re-implement it, HashSet reuses HashMap and ignores the values.

2How HashSet Delegates to HashMap

Inside the JDK, HashSet has one important field, a HashMap, and one constant, a shared Object used as the value of every entry. A simplified version of the source looks like this.

Java
public class HashSet<E> implements Set<E> /* ... */ {
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object(); // one dummy value for all entries
public HashSet() { map = new HashMap<>(); }
public boolean add(E e) { return map.put(e, PRESENT) == null; }
public boolean remove(Object o) { return map.remove(o) == PRESENT; }
public boolean contains(Object o){ return map.containsKey(o); }
public int size() { return map.size(); }
public Iterator<E> iterator() { return map.keySet().iterator(); }
}
Step throughWhat sits under a HashSet
  1. HashSet<E>add, remove, contains, iterator
  2. HashMap<E, Object>element as key, PRESENT as value
  3. Table of binsarray sized to a power of two, resized at 75% full
  4. Nodes or tree nodeshash, key, value, next; trees for crowded bins

4 layers, from the top down. Step through them one at a time.

Every rule of HashMap applies to the set above it.

Notice that every operation is one call on the map. The elements are the map's keys, and iteration over the set is iteration over the map's key set. Using a single shared PRESENT object means the values cost nothing beyond the reference in each entry. LinkedHashSet uses the same trick with a LinkedHashMap underneath, which is why it keeps insertion order.

3How add() Reports Whether the Element Was New

HashMap.put returns the previous value for the key, or null if there was no mapping. HashSet relies on that. If the element was not in the set, put adds a new entry and returns null, so add returns true. If an equal element was already there, put replaces its value with PRESENT, which is the same object anyway, and returns the old value, PRESENT, which is not null, so add returns false.

Java
Set<String> tags = new HashSet<>();
tags.add("java"); // true: put returned null, a new key
tags.add("spring"); // true
tags.add("java"); // false: put returned PRESENT, the key existed
tags.size(); // 2

One detail is worth knowing: when an equal element already exists, the set keeps the original element object and does not store the new one, because put only replaces the value, not the key. If two equal objects differ in fields that equals ignores, the set holds whichever came first.

4The HashMap Rules HashSet Inherits

Because the elements are HashMap keys, everything we know about HashMap keys applies. Elements are found by hashCode and then equals, so a class used in a HashSet must override both consistently. A poor hashCode crowds elements into few bins and slows every operation; Java 8's tree bins limit the damage when a bin passes 8 elements in a table of at least 64 bins. The set starts with 16 bins and doubles when it passes 75% full, the load factor, so if we know the size in advance, HashSet.newHashSet(n), available since Java 19, avoids repeated resizing.

The most important inherited rule concerns mutation. An element is placed in a bin according to its hash at the time of insertion. If a field used by hashCode changes afterwards, the element stays in its old bin while lookups go to the new one.

Java
class Tag {
String name;
Tag(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Tag t && t.name.equals(name); }
@Override public int hashCode() { return name.hashCode(); }
}
Set<Tag> set = new HashSet<>();
Tag t = new Tag("java");
set.add(t);
t.name = "kotlin"; // hash changes while inside the set
set.contains(t); // false: looks in the bin for "kotlin"
set.remove(t); // false: cannot find it either
set.size(); // 1: the element is stranded

This is the same lost-entry bug as a mutable HashMap key, and it is a memory leak if it repeats. Elements of hash-based sets should be immutable, and records or final fields are the simple way to guarantee it.

5Null Elements and Thread Safety

HashMap allows one null key, so HashSet allows one null element, stored in bin 0 because HashMap treats the hash of null as 0. Adding null twice returns true and then false, like any other element. Set.of and other immutable sets, by contrast, reject null.

HashMap is not thread-safe, so neither is HashSet. Concurrent adds can lose elements or corrupt the table, and iterating while another thread modifies the set may throw ConcurrentModificationException. For a concurrent set, we use ConcurrentHashMap.newKeySet(), which applies the same wrapping idea to ConcurrentHashMap, or Collections.synchronizedSet for simple cases.

6Follow-up questions

Why does remove() compare the result with PRESENT instead of checking for null?

HashMap.remove returns the removed value, or null if there was no mapping. Every value in the set's map is PRESENT, so a successful removal returns PRESENT, and comparing with it is a direct way to say the element was there. It is equivalent to checking for non-null here.

Is a HashSet more memory-efficient than a HashMap?

No. It is a HashMap, so each element costs a full map node with hash, key, value and next fields, plus the table slot. The value field always points to the shared PRESENT object, so the only saving is that we do not allocate separate value objects.

7Conclusion

In this answer, we saw that HashSet wraps a HashMap<E, Object>, storing each element as a key mapped to a shared dummy value, PRESENT. add(e) calls map.put(e, PRESENT) and returns true when put returns null, meaning the element was absent. As a result, HashSet inherits all of HashMap's behaviour: hashing, bins, tree bins, resizing and the load factor, equality through equals and hashCode, lost elements when mutable elements change, one allowed null, and no thread safety.

What to say in the interviewAbout 90 seconds aloud

Open with

HashSet is basically a HashMap in disguise. It has a private HashMap where the elements are the keys, and every key maps to the same static dummy object called PRESENT. add calls map.put of the element and PRESENT, and returns whether put returned null. put returns the previous value for the key, so null means the key was absent and the element is new, and add returns true.

Then, if they want more

If an equal element was already there, put returns PRESENT, so add returns false, and the original element object is kept. remove and contains are also one call each on the map, and iteration is over the map's key set.

Because of that, all the HashMap rules apply: elements are located by hashCode and then equals, so both must be overridden consistently; a poor hashCode crowds bins, with tree bins limiting the damage since Java 8; the table starts at 16 and doubles past the 0.75 load factor, so newHashSet with an expected size avoids resizes.

Mutable elements are dangerous: if a field used in hashCode changes after insertion, the element is stranded in its old bin and contains and remove both fail. It allows one null element, like HashMap allows one null key, and it is not thread-safe; for a concurrent set I would use ConcurrentHashMap.newKeySet.

About this answer

Last updated
12 November 2026
Versions it names
Java 19, Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How is java.util.HashSet implemented, and how does add() report whether the element was...": https://scrivio-interview-library.netlify.app/java/sets/d0d8df95e3/