Difficulty: Intermediate
How does HashSet ensure uniqueness internally? What happens if you mutate an object after adding it to a HashSet?
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.
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.
HashSet, HashMap, Uniqueness, Mutable Keys, LinkedHashSet