Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How does a HashSet avoid storing duplicates in Java?

SHORT ANSWER

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

java
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: 2

What 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.

#java#collections#hashset

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.