Java Notes
Learn Java HashSet — storing unique elements, how duplicates are detected using equals and hashCode, common operations, and when to use HashSet over other Set implementations.
HashSet stores a collection of unique elements. If you try to add something that already exists, the add does nothing — no error, no duplicate. This makes it perfect for problems where you need to track "have I seen this before?"
There is no guaranteed order. If you need sorted order, use TreeSet. If you need insertion order, use LinkedHashSet.
Creating and Using HashSet
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
cities.add("Delhi")twice — second add returnsfalseand the set stays unchanged.cities.size()returns 3 — only unique values counted.contains()is O(1) — very fast lookup, regardless of set size.- Iteration order is unpredictable — do not assume any order.
How HashSet Detects Duplicates
HashSet internally uses a HashMap. When you add(element), it computes element.hashCode() to find the bucket, then uses equals() to check if an identical element exists. If both match, the element is a duplicate and is rejected.
This means: if you store custom objects, you must override both equals() and hashCode().
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
- Two students with rollNo "101" —
hashCode()gives same bucket,equals()says same rollNo → duplicate rejected. - Without overriding, two different
Studentobjects would never be equal (defaultequalscompares references).
Common Set Operations
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Common Mistake 1: Forgetting to Override hashCode()
static class Product {
String id;
Product(String id) { this.id = id; }
@Override
public boolean equals(Object o) {
return o instanceof Product && ((Product) o).id.equals(this.id);
}
// Missing hashCode() — equal objects may end up in different buckets!
}
Set<Product> set = new HashSet<>();
set.add(new Product("A1"));
set.add(new Product("A1")); // NOT detected as duplicate without hashCode!
System.out.println(set.size()); // 2 — wrong! Expected 1Always override both equals() and hashCode() together.
Common Mistake 2: Assuming HashSet Has a Specific Order
If order matters, use TreeSet (sorted) or LinkedHashSet (insertion order).
Practice Task
Task: Given two arrays of names: {"Asha", "Ravi", "Priya", "Asha", "Dev"} and {"Ravi", "Kiran", "Dev", "Neha"}, use HashSet to:
- Find unique names across both arrays combined
- Find names that appear in both arrays (intersection)
- Find names only in the first array (difference)
Hint: Create a HashSet from each array using new HashSet<>(Arrays.asList(...)). Use addAll for union, retainAll for intersection, removeAll for difference (on copies so originals are not modified).
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: set1 from arr1 automatically deduplicates "Asha" — it appears once. The intersection gives {Ravi, Dev}. Notice you work on copies (new HashSet<>(set1)) so the original sets are unchanged after each operation.
Continue the lesson path