Syllabus / Java / Phase 4: Collections & Error Handling (Days 17–21)
Beginner

The Set Interface

📂 Phase 4: Collections & Error Handling (Days 17–21) · Java

A Set is like a guest list — every value can appear only once. Adding a duplicate is silently ignored rather than throwing an error.

Basic Set Usage

Set attendees = new HashSet<>();
attendees.add("Alice");
attendees.add("Bob");
attendees.add("Alice");  // ignored — already exists

System.out.println(attendees.size()); // 2, not 3

HashSet vs LinkedHashSet vs TreeSet

ImplementationOrderingPerformance
HashSetNo guaranteed orderFastest — O(1) add/lookup
LinkedHashSetPreserves insertion orderSlightly slower than HashSet
TreeSetAlways sorted (natural or custom order)O(log n) operations

TreeSet Example — Automatic Sorting

Set treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
System.out.println(treeSet); // [Apple, Banana, Cherry] — sorted automatically

Why Sets Matter

Sets are the natural choice whenever uniqueness is a requirement — tracking unique visitors, removing duplicate entries from a dataset, or storing a collection of distinct IDs.

List numbersWithDuplicates = Arrays.asList(1, 2, 2, 3, 3, 3, 4);
Set uniqueNumbers = new HashSet<>(numbersWithDuplicates);
System.out.println(uniqueNumbers); // [1, 2, 3, 4] — duplicates removed instantly
Interview tip: HashSet internally uses a HashMap to guarantee uniqueness — each element you add becomes a key in that internal HashMap, with a placeholder value. This is why HashSet inherits HashMap's O(1) average performance.