Lesson 38: Working with the Set Interface
The Set interface models the mathematical concept of a set: an unordered collection that contains only unique elements.
1. HashSet
- Implementation: Uses a hash table for storage (relies on object hashing).
- Performance: Provides constant time (O(1)) performance for basic operations like
add(),remove(), andcontains(), assuming a good hash function. - Order: Does not guarantee insertion order.
java import java.util.HashSet; import java.util.Set;
Set<String> uniqueColors = new HashSet<>(); uniqueColors.add("Red"); uniqueColors.add("Blue"); boolean added = uniqueColors.add("Red"); // Returns false, Red already exists
System.out.println(uniqueColors.size()); // Output: 2
// Iterating a Set (order is not guaranteed) for (String color : uniqueColors) { System.out.println(color); }
2. LinkedHashSet
- Maintains insertion order (iterates in the order elements were added).
- Slightly slower than
HashSetdue to the overhead of maintaining the linked list structure.
3. TreeSet
- Implementation: Uses a tree structure (Red-Black Tree).
- Order: Stores elements in their natural sorted order (or by a custom Comparator).
- Performance: Operations are generally O(log N) (logarithmic time), making it slower than
HashSetbut necessary if sorted output is required.
java import java.util.TreeSet;
TreeSet<Integer> sortedNumbers = new TreeSet<>(); sortedNumbers.add(50); sortedNumbers.add(10); sortedNumbers.add(30);
// Output: [10, 30, 50] (Always sorted) System.out.println(sortedNumbers);