How does a HashSet avoid storing duplicates in Java?
A HashSet is backed by a HashMap and stores each element as a key. add() uses hashCode to find the bucket and equals to check for an existing equal element; if one exists the add returns false and nothing is stored.
Explain it simply
Think of a college attendance register where each roll number has a fixed row. Before writing a new name, you go to that row and see if the same student is already listed. If yes, you skip. A HashSet does that check with hashCode (find the row) and equals (compare the entry).
Example
import java.util.*;
Set<String> cities = new HashSet<>();
System.out.println(cities.add("Pune")); // prints: true
System.out.println(cities.add("Delhi")); // prints: true
System.out.println(cities.add("Pune")); // prints: false (already present)
System.out.println(cities.size()); // prints: 2What to say in the interview
"HashSet wraps a HashMap, and the elements are the map's keys with a dummy constant as the value. On add, it computes the hash, goes to the bucket, and compares with equals. So for custom classes to work as set elements, they must override both equals and hashCode consistently. Add, remove and contains are O(1) on average, and the iteration order is not guaranteed."
Common mistakes
- Adding custom objects without overriding equals and hashCode, then wondering why duplicates appear.
- Expecting insertion order. Use LinkedHashSet for that.