2.3 Sets Explained
Sets in Java are a fundamental part of the Java Collections Framework, providing a way to store and manipulate collections of unique elements. Understanding sets is crucial for managing collections where duplicates are not allowed.
Key Concepts
1. Set Interface
The Set interface extends the Collection interface and represents a collection of unique elements. It does not allow duplicate elements and does not guarantee any specific order.
Example
Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, will not be added
System.out.println(set); // Output: [Apple, Banana]
2. HashSet
A HashSet is a collection that uses a hash table for storage. It provides constant-time performance for basic operations like add, remove, and contains. The order of elements is not guaranteed.
Example
Set hashSet = new HashSet<>();
hashSet.add(10);
hashSet.add(20);
hashSet.add(30);
System.out.println(hashSet); // Output: [20, 10, 30] (order may vary)
3. LinkedHashSet
A LinkedHashSet maintains the insertion order of elements. It provides constant-time performance for basic operations and maintains a doubly-linked list running through all of its entries.
Example
Set linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Dog");
linkedHashSet.add("Cat");
linkedHashSet.add("Bird");
System.out.println(linkedHashSet); // Output: [Dog, Cat, Bird]
4. TreeSet
A TreeSet stores elements in a sorted order. It uses a red-black tree structure and provides logarithmic-time performance for basic operations. The elements are sorted according to their natural ordering or by a specified comparator.
Example
Set treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
System.out.println(treeSet); // Output: [Apple, Banana, Cherry]
Examples and Analogies
Think of a Set as a unique collection of items, similar to a bag that can only hold one of each type of item. A HashSet is like a bag where items are stored without any specific order, a LinkedHashSet is like a bag where items are stored in the order they were added, and a TreeSet is like a bag where items are stored in a sorted order.
By mastering sets, you can efficiently manage and manipulate collections of unique elements in your Java SE 11 applications.