Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Sets solve a small family of problems very well: drop duplicates, check "seen before?" fast, keep values sorted, and compare groups. Most bugs with sets come from a handful of mistakes that are easy to spot once you know them.

Choosing the right set

Ask two questions. First, what order do you need? None → HashSet. The order of adding → LinkedHashSet. Sorted, or "next value after x" → TreeSet. The example below uses all three.

Example 1 · One list, three jobs, three sets

RightSetDemo.javaJava
import java.util.HashSet;import java.util.LinkedHashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
public class RightSetDemo {    public static void main(String[] args) {        List<String> signUps = List.of("neha@gmail.com", "arjun@yahoo.in", "neha@gmail.com",                "zaid@gmail.com", "bhavna@outlook.com", "arjun@yahoo.in");
        Set<String> inOrder = new LinkedHashSet<>(signUps);        System.out.println("Registration order: " + inOrder);
        Set<String> sorted = new TreeSet<>(signUps);        System.out.println("For the printed list: " + sorted);
        Set<String> lookup = new HashSet<>(signUps);        String email = "zaid@gmail.com";        System.out.println(email + " registered? " + lookup.contains(email));        System.out.println("Duplicate sign-ups: " + (signUps.size() - lookup.size()));    }}
Output
Registration order: [neha@gmail.com, arjun@yahoo.in, zaid@gmail.com, bhavna@outlook.com]
For the printed list: [arjun@yahoo.in, bhavna@outlook.com, neha@gmail.com, zaid@gmail.com]
zaid@gmail.com registered? true
Duplicate sign-ups: 2

What this code does

  • The same data goes into the set that fits each job: LinkedHashSet to show who came first, TreeSet for an alphabetical list, HashSet for fast lookups.
  • The number of duplicates is simply the list size minus the set size: 6 − 4 = 2.

Second, how does the set decide "same"? HashSet and LinkedHashSet use hashCode and equals, so your class needs both. TreeSet uses compareTo or the comparator, so it needs an order where 0 means "really the same entry".

Four patterns worth remembering

When a problem says "unique", "distinct", "already", "common" or "missing", a set is usually the right tool.

SeenBefore.javaJava
import java.util.*;
public class SeenBefore {    public static void main(String[] args) {        List<String> txns = List.of("UPI101", "UPI102", "UPI101", "UPI103", "UPI102");        Set<String> seen = new HashSet<>();        for (String id : txns) {            if (!seen.add(id)) {                System.out.println("Repeat: " + id);            }        }        System.out.println(new LinkedHashSet<>(txns));        System.out.println(new TreeSet<>(txns).last());    }}
Output
Repeat: UPI101
Repeat: UPI102
[UPI101, UPI102, UPI103]
UPI103
  • Seen before? if (!seen.add(x)) detects a repeat in O(1).
  • Drop duplicates: new HashSet<>(list), or new LinkedHashSet<>(list) to keep the order.
  • Sorted and unique: a TreeSet, plus first, last, floor and ceiling for neighbours.
  • Compare groups: copy, then addAll, retainAll or removeAll; containsAll for "has everything".

The mistakes that cost marks

These are the bugs seen most often in sets code, in lab exams and in real projects. Each one compiles, so the compiler will not save you.

Java
Set<String> cse = new HashSet<>(List.of("Asha", "Ravi", "Meena"));Set<String> ece = new HashSet<>(List.of("Ravi", "Kiran"));Set<String> common = new HashSet<>(cse);   // copy first...common.retainAll(ece);                     // ...so cse is unchangedSet<String> bad = Set.of("Asha", "Asha");  // IllegalArgumentException: duplicate element: Asha
  • Trusting HashSet order, or looking for get(index). Sort a copy or pick another set.
  • Overriding equals without hashCode, or changing a key field after add.
  • A TreeSet comparator that returns 0 for different entries, so they vanish. Add a tie-breaker.
  • Calling retainAll/removeAll on the original set, or using Set.of with repeats. Copy first; use HashSet for messy data.

Removing while you loop

Like lists, sets do not allow set.remove(x) inside a for-each loop over the same set. The loop notices that the set changed behind its back and throws ConcurrentModificationException.

Example 2 · Mistake: removing inside a for-each loop

LoopRemoveDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class LoopRemoveDemo {    public static void main(String[] args) {        Set<Integer> marks = new TreeSet<>(Set.of(45, 82, 30, 91, 67, 25));        System.out.println("Marks: " + marks);
        for (int m : marks) {            if (m < 40) {                marks.remove(m);            }        }        System.out.println("Passed: " + marks);    }}
Sample output
Marks: [25, 30, 45, 67, 82, 91]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1486)
	at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1540)
	at LoopRemoveDemo.main(LoopRemoveDemo.java:9)

What this code does

  • 25 is removed during the loop. When the loop asks for the next value, the hidden iterator sees the set was changed and stops the program.
  • Line 9 is the for-each line: the crash comes from the loop itself, not from remove.

Example 3 · Fix: removeIf or Iterator.remove

SafeRemoveDemo.javaJava
import java.util.Iterator;import java.util.Set;import java.util.TreeSet;
public class SafeRemoveDemo {    public static void main(String[] args) {        Set<Integer> marks = new TreeSet<>(Set.of(45, 82, 30, 91, 67, 25));        marks.removeIf(m -> m < 40);        System.out.println("Passed: " + marks);
        Set<String> tickets = new TreeSet<>(Set.of("T101-used", "T102", "T103-used", "T104"));        Iterator<String> it = tickets.iterator();        while (it.hasNext()) {            String t = it.next();            if (t.endsWith("-used")) {                it.remove();                System.out.println("Cancelled " + t);            }        }        System.out.println("Valid tickets: " + tickets);    }}
Output
Passed: [45, 67, 82, 91]
Cancelled T101-used
Cancelled T103-used
Valid tickets: [T102, T104]

What this code does

  • removeIf takes a lambda that answers "remove this one?" and does the looping safely for you.
  • With an Iterator, it.remove() removes the value just returned by next() without upsetting the loop. Use it when you need to do more work per value, like printing.

The safe ways are the same as for lists. set.removeIf(x -> x < 40) removes every match in one call. Or use an Iterator and call it.remove(), which removes the current value safely.

Fix the error

Fix the set mistake

Read the error, then pick the line that fixes it.

Round 1 of 2

Remove every mark below 40 from the set.

Set<Integer> marks = new HashSet<>(List.of(35, 72, 28, 90));
for (int m : marks) { if (m < 40) marks.remove(m); }
System.out.println(marks);

Error

Exception in thread "main" java.util.ConcurrentModificationException
A TreeSet also has headSet(40).clear(): the view is live, so clearing it removes those values from the set itself.

Example 4 · Everything together: a quiz contest report

QuizContestDemo.javaJava
import java.util.Comparator;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
record Entry(int roll, String name) {}
public class QuizContestDemo {    public static void main(String[] args) {        Entry[] round1 = {            new Entry(12, "Tanvi"), new Entry(5, "Kiran"), new Entry(12, "Tanvi"),            new Entry(8, "Om"), new Entry(3, "Lata")        };        Entry[] round2 = {            new Entry(5, "Kiran"), new Entry(21, "Yash"), new Entry(3, "Lata"), new Entry(21, "Yash")        };        Set<Entry> lastYear = Set.of(new Entry(5, "Kiran"), new Entry(30, "Riya"));
        Comparator<Entry> byName = Comparator.comparing((Entry e) -> e.name())                .thenComparingInt(e -> e.roll());
        Set<Entry> r1 = new HashSet<>();        int repeats = 0;        for (Entry e : round1) {            if (!r1.add(e)) {                repeats++;            }        }        Set<Entry> r2 = new HashSet<>(List.of(round2));
        Set<Entry> both = new TreeSet<>(byName);        both.addAll(r1);        both.retainAll(r2);
        Set<Entry> everyone = new TreeSet<>(byName);        everyone.addAll(r1);        everyone.addAll(r2);
        Set<Entry> firstTimers = new TreeSet<>(byName);        firstTimers.addAll(everyone);        firstTimers.removeAll(lastYear);
        System.out.println("Repeated submissions in round 1: " + repeats);        System.out.println("Played both rounds:");        for (Entry e : both) {            System.out.println("  " + e.name() + " (" + e.roll() + ")");        }        System.out.println("Participants: " + everyone.size());        System.out.print("First-timers:");        for (Entry e : firstTimers) {            System.out.print(" " + e.name());        }        System.out.println();    }}
Output
Repeated submissions in round 1: 1
Played both rounds:
  Kiran (5)
  Lata (3)
Participants: 5
First-timers: Lata Om Tanvi Yash

What this code does

  • Records give correct equals and hashCode, so repeats are caught by add and set maths works. The TreeSets use a comparator with a roll-number tie-breaker so two students with the same name are never merged.
  • retainAll and removeAll call contains on the argument (r2, lastYear), which use the records' equals and hashCode. The TreeSets only control the printed order.

Finish up

Mark complete & continue

Next: Must-do problems: Sets