Lesson Completion
Back to course

Set Interface: Collections of Unique Elements

Intermediate
20 minutes4.7Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: Set stores unique elements only—no duplicates allowed.
  • Main implementations: HashSet (fastest, no order), LinkedHashSet (insertion order maintained), TreeSet (sorted order). Use Sets for membership testing, removing duplicates, and mathematical set operations.

Think of email contacts list. You can't have "alice@example.com" twice—each contact is unique. Add it again? Ignored. That's a Set!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Guest List

  • HashSet: Random seating (fastest check-in, no order)
  • LinkedHashSet: Arrival order seating (remember who came first)
  • TreeSet: Alphabetical seating (sorted by name)

3. Technical Mastery (The "Deep Dive")

Implementations Comparison

FeatureHashSetLinkedHashSetTreeSet
OrderingNoneInsertion orderSorted (natural/comparator)
PerformanceO(1)O(1)O(log n)
NullOne null allowedOne null allowedNo nulls
Use CaseDefault (fastest)Need insertion orderNeed sorted data

4. Interactive & Applied Code

java
import java.util.*; public class SetDemo { public static void main(String[] args) { // HASHSET: Fastest, no order Set<String> hashSet = new HashSet<>(); hashSet.add("Banana"); hashSet.add("Apple"); hashSet.add("Banana"); // ❌ Duplicate ignored System.out.println("HashSet: " + hashSet); // [Banana, Apple] (random order) // LINKEDHASHSET: Maintains insertion order Set<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("Banana"); linkedHashSet.add("Apple"); linkedHashSet.add("Cherry"); System.out.println("LinkedHashSet: " + linkedHashSet); // [Banana, Apple, Cherry] // TREESET: Sorted order Set<String> treeSet = new TreeSet<>(); treeSet.add("Banana"); treeSet.add("Apple"); treeSet.add("Cherry"); System.out.println("TreeSet: " + treeSet); // [Apple, Banana, Cherry] // Set operations Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3)); Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5)); // Union Set<Integer> union = new HashSet<>(set1); union.addAll(set2); System.out.println("Union: " + union); // [1, 2, 3, 4, 5] // Intersection Set<Integer> intersection = new HashSet<>(set1); intersection.retainAll(set2); System.out.println("Intersection: " + intersection); // [3] // Difference Set<Integer> difference = new HashSet<>(set1); difference.removeAll(set2); System.out.println("Difference: " + difference); // [1, 2] // Membership test (O(1) for HashSet) System.out.println("Contains 2? " + hashSet.contains("Banana")); } }

5. The Comparison & Decision Layer

Decision Tree: Choosing a Set

graph TD A{Need sorted order?} A -- Yes --> B[TreeSet] A -- No --> C{Need insertion order?} C -- Yes --> D[LinkedHashSet] C -- No --> E[HashSet]

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "How does HashSet prevent duplicates?" Answer: HashSet uses HashMap internally. When you add an element:

  1. Calls element.hashCode() to find bucket
  2. Calls element.equals() to check if already exists in that bucket
  3. If exists, add() returns false (duplicate rejected)

Critical: Override both hashCode() and equals() together!

Pro-Tip: Remove duplicates from List:

java
List<String> listWithDupes = Arrays.asList("A", "B", "A", "C"); Set<String> unique = new LinkedHashSet<>(listWithDupes); // Preserves order! List<String> result = new ArrayList<>(unique); System.out.println(result); // [A, B, C]

Topics Covered

Java FundamentalsData Structures

Tags

#java#collections#list#set#map#arraylist#hashmap

Last Updated

2025-02-01