HashSet Internals and Duplicates
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)"How does a HashSet reject duplicates?" is a favourite follow-up to the HashMap question. The interviewer is checking that you link the set to its map, know the equals and hashCode contract, and can predict a set size for custom objects.
HashSet is a HashMap with a dummy value
A HashSet is a Set that stores each element as a key inside a HashMap, with one shared dummy value. A set holds no duplicates, so adding an element that is already there changes nothing.
A HashSet reuses the HashMap you already know. The program shows that add returns false for a duplicate and that one null is allowed.
Example 1 · add returns false for a duplicate
import java.util.HashSet;import java.util.Set;
public class AddResultDemo { public static void main(String[] args) { Set<String> visitors = new HashSet<>(); System.out.println("add Asha: " + visitors.add("Asha")); System.out.println("add Ravi: " + visitors.add("Ravi")); System.out.println("add Asha: " + visitors.add("Asha")); System.out.println("add null: " + visitors.add(null)); System.out.println("add null: " + visitors.add(null)); System.out.println("size " + visitors.size() + ", has Ravi? " + visitors.contains("Ravi")); }}add Asha: true add Ravi: true add Asha: false add null: true add null: false size 3, has Ravi? true
What this code does
addismap.put(e, PRESENT) == null. The second Asha finds an old value, soputreturnsPRESENTandaddreturnsfalse.- One
nullis allowed, just like HashMap's one null key.
Inside every HashSet is a field map of type HashMap<E, Object> and one shared constant called PRESENT. add(e) runs map.put(e, PRESENT) == null: it returns true when the element was new and false when it was already there. Revise: HashSet (opens in a new tab).
So a HashSet has the same speed as a HashMap, O(1) on average, the same 0.75 load factor, and allows one null. In short:
add→map.put(e, PRESENT) == null→trueif new.contains(e)→map.containsKey(e);remove(e)→map.remove(e) == PRESENT.LinkedHashSetuses aLinkedHashMap;TreeSetuses aTreeMap.- Default 16 buckets, load factor 0.75, one
nullelement allowed.
How duplicates are detected: hashCode, then equals
A HashSet finds a duplicate in two steps. hashCode picks the bucket and the stored hash is compared; only on a match does equals confirm. Both methods must agree for the check to work.
A set must decide when two elements are the same. The program prints every hashCode and equals call made while adding names.
Example 2 · Watching hashCode and equals being called
import java.util.HashSet;import java.util.Set;
class Student { final String name;
Student(String name) { this.name = name; }
@Override public int hashCode() { System.out.println(" hashCode(" + name + ")"); return name.hashCode(); }
@Override public boolean equals(Object o) { boolean same = o instanceof Student s && s.name.equals(name); String other = (o instanceof Student s) ? s.name : "?"; System.out.println(" equals(" + name + ", " + other + ") -> " + same); return same; }}
public class DuplicateCheckDemo { public static void main(String[] args) { Set<Student> set = new HashSet<>(); System.out.println("add Asha #1"); System.out.println(" result " + set.add(new Student("Asha"))); System.out.println("add Ravi"); System.out.println(" result " + set.add(new Student("Ravi"))); System.out.println("add Asha #2"); System.out.println(" result " + set.add(new Student("Asha"))); System.out.println("size " + set.size()); }}add Asha #1 hashCode(Asha) result true add Ravi hashCode(Ravi) result true add Asha #2 hashCode(Asha) equals(Asha, Asha) -> true result false size 2
What this code does
- Every
addcallshashCodefirst. Ravi lands in the same bucket as Asha, but the stored hashes differ, soequalsis skipped. - Only the second Asha has a matching hash, so
equalsruns once, returnstrue, and the element is rejected.
equals is not called for every element, only for real hash matches. That is why both methods must agree: equal objects must have equal hash codes, or the set looks in the wrong bucket and never calls equals at all. Revise: equals and hashCode in collections (opens in a new tab).
Order of execution
How add finds a duplicate
A second "Asha" is added to a HashSet. Put the steps in the order the set runs them.
equals is never called for Ravi, because the stored hash codes differ.HashSet vs LinkedHashSet vs TreeSet
A TreeSet is a Set that keeps its elements sorted. It is backed by a TreeMap, so operations take O(log n), and duplicates are decided by compareTo or a Comparator, never by equals.
The three sets differ in order, speed and the way they find duplicates. The program adds the same names to each one and prints the results.
Example 3 · Three sets, three orders, two duplicate rules
import java.util.HashSet;import java.util.LinkedHashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
public class ThreeSetsDemo { public static void main(String[] args) { List<String> names = List.of("Ravi", "asha", "Kiran", "Asha", "Ravi");
Set<String> hash = new HashSet<>(names); Set<String> linked = new LinkedHashSet<>(names); Set<String> tree = new TreeSet<>(names); Set<String> ignoreCase = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); ignoreCase.addAll(names);
System.out.println("HashSet " + hash); System.out.println("LinkedHashSet " + linked); System.out.println("TreeSet " + tree); System.out.println("TreeSet (ignore case) " + ignoreCase); }}HashSet [Kiran, Ravi, Asha, asha] LinkedHashSet [Ravi, asha, Kiran, Asha] TreeSet [Asha, Kiran, Ravi, asha] TreeSet (ignore case) [asha, Kiran, Ravi]
What this code does
- LinkedHashSet keeps the first-seen order; TreeSet sorts, and capital letters come before small letters in
Stringorder. - The case-insensitive TreeSet sees "asha" and "Asha" as equal because the comparator returns 0, so only the first one stays.
equalsis never used.
The three sets side by side:
- HashSet: no order, O(1), one null.
- LinkedHashSet: insertion order, O(1), one null.
- TreeSet: sorted, O(log n), no null (natural order), duplicates by
compareTo; offersfirst,floor,ceilinganddescendingSet.
The trap: a TreeSet does not use equals or hashCode. It decides duplicates with compareTo or its Comparator. A case-insensitive comparator therefore treats "Asha" and "asha" as the same element and keeps only the first. Revise: LinkedHashSet and TreeSet (opens in a new tab).
Predict the output: custom objects in a set
A favourite written-round question: two objects with the same data go into a HashSet, and you give the size. The program tries three versions of the class.
Example 4 · Same data, different set sizes
import java.util.HashSet;import java.util.Set;
class PlainSeat { final int number;
PlainSeat(int number) { this.number = number; }}
class EqualsOnlySeat { final int number;
EqualsOnlySeat(int number) { this.number = number; }
@Override public boolean equals(Object o) { return o instanceof EqualsOnlySeat s && s.number == number; }}
record Seat(int number) {}
public class SeatSetDemo { public static void main(String[] args) { Set<PlainSeat> plain = new HashSet<>(); plain.add(new PlainSeat(23)); plain.add(new PlainSeat(23));
Set<EqualsOnlySeat> equalsOnly = new HashSet<>(); equalsOnly.add(new EqualsOnlySeat(23)); equalsOnly.add(new EqualsOnlySeat(23));
Set<Seat> seats = new HashSet<>(); seats.add(new Seat(23)); seats.add(new Seat(23));
System.out.println("No overrides: size " + plain.size()); System.out.println("equals only: size " + equalsOnly.size()); System.out.println("record: size " + seats.size()); System.out.println("record contains Seat[23]? " + seats.contains(new Seat(23))); }}No overrides: size 2 equals only: size 2 record: size 1 record contains Seat[23]? true
What this code does
- Without a matching
hashCode, the twoEqualsOnlySeatobjects get different identity hash codes, so the set never compares them withequals. - A record generates
equalsandhashCodefrom its fields, so the secondSeat(23)is a duplicate.
The size depends on which methods the class overrides:
- Neither
equalsnorhashCode: identity is compared, so size 2. - Only
equals: hash codes differ, so different buckets and size 2 (in practice). - Only
hashCode: same bucket, butequalscompares identity, so size 2. - Both, or a
record: size 1. Records generate both from their components.
Revise: Sets of objects (opens in a new tab).
Predict the output
Predict the set size
Two objects with the same number go into a set. Pick the result.
Round 1 of 3
Only hashCode is overridden. What is the size?
Coding question: remove duplicates while keeping order
Order-preserving de-duplication removes repeated values and keeps the first copy of each in its original position. A LinkedHashSet does it in one pass, O(n).
Remove repeats and keep the original order. The program uses a LinkedHashSet, finds the first repeat with the return value of add, and repeats the idea with streams.
Example 5 · De-duplicate tokens and find the first repeat
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.List;import java.util.Set;
public class DedupDemo { static List<Integer> dedupKeepOrder(int[] values) { Set<Integer> seen = new LinkedHashSet<>(); for (int v : values) { seen.add(v); } return new ArrayList<>(seen); }
static int firstRepeated(int[] values) { Set<Integer> seen = new HashSet<>(); for (int v : values) { if (!seen.add(v)) { return v; } } return -1; }
static String uniqueChars(String text) { Set<Character> seen = new LinkedHashSet<>(); for (char c : text.toCharArray()) { seen.add(c); } StringBuilder sb = new StringBuilder(); for (char c : seen) { sb.append(c); } return sb.toString(); }
public static void main(String[] args) { int[] tokens = {4, 2, 4, 7, 2, 9, 7}; System.out.println("Unique in order: " + dedupKeepOrder(tokens)); System.out.println("First repeat: " + firstRepeated(tokens)); System.out.println("With streams: " + Arrays.stream(tokens).distinct().boxed().toList()); System.out.println("Unique letters: " + uniqueChars("programming")); }}Unique in order: [4, 2, 7, 9] First repeat: 4 With streams: [4, 2, 7, 9] Unique letters: progamin
What this code does
- LinkedHashSet keeps the first copy of each token in its original position, in one O(n) pass.
!seen.add(v)is true exactly when v was already seen, so the first repeat is found without a nested loop.distinct()keeps encounter order for ordered streams;toList()needs Java 16 or later.
A LinkedHashSet does it in one pass, O(n): add everything, then read the set back.
Related favourites use add's return value: if (!seen.add(x)) means x is a repeat, which finds the first repeated element in O(n). For streams, distinct() also keeps encounter order.
Fix the error
Fix the duplicate checks
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Print every value that was already seen.
Error
FirstRepeat.java:7: error: bad operand types for binary operator '=='
if (seen.add(x) == null) {
^Next step
Check your understanding
12 quick questions