Set in Java: HashSet, LinkedHashSet, TreeSet
Introduction
In Java, the Set interface is part of the java.util package. It represents a collection that does not allow duplicate elements. Common implementations of the Set interface include:
- HashSet
- LinkedHashSet
- TreeSet
1. HashSet
A HashSet is an unordered collection that uses a hash table for storage. It does not guarantee the order of elements.
Example: Using HashSet
import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { // Create a HashSet HashSetset = new HashSet<>(); // Add elements to the HashSet set.add("Apple"); set.add("Banana"); set.add("Cherry"); // Attempt to add duplicate elements set.add("Apple"); // Display the HashSet System.out.println("HashSet: " + set); // Check if an element exists System.out.println("Contains 'Banana': " + set.contains("Banana")); // Remove an element set.remove("Banana"); System.out.println("After removal: " + set); // Iterate over the HashSet for (String fruit : set) { System.out.println(fruit); } } }
2. LinkedHashSet
A LinkedHashSet is an ordered version of HashSet that maintains a linked list of the entries in the order they were inserted.
Example: Using LinkedHashSet
import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String[] args) { // Create a LinkedHashSet LinkedHashSetset = new LinkedHashSet<>(); // Add elements to the LinkedHashSet set.add("Dog"); set.add("Cat"); set.add("Rabbit"); // Display the LinkedHashSet System.out.println("LinkedHashSet: " + set); // Add a duplicate element set.add("Cat"); // Iterate over the LinkedHashSet for (String animal : set) { System.out.println(animal); } } }
3. TreeSet
A TreeSet is a NavigableSet implementation that uses a tree for storage. It maintains elements in their natural order or a specified comparator's order.
Example: Using TreeSet
import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { // Create a TreeSet TreeSetset = new TreeSet<>(); // Add elements to the TreeSet set.add("Orange"); set.add("Apple"); set.add("Banana"); // Display the TreeSet System.out.println("TreeSet: " + set); // Attempt to add a duplicate element set.add("Apple"); // Display elements in sorted order for (String fruit : set) { System.out.println(fruit); } } }
Differences Between HashSet, LinkedHashSet, and TreeSet
Feature | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Ordering | No order | Maintains insertion order | Sorted order |
Performance | Fast (O(1) for add, remove, contains) | Fast (O(1) for add, remove, contains) | Slower (O(log n) for add, remove, contains) |
Null Elements | Allows one null | Allows one null | Does not allow null |
Conclusion
Each Set implementation has its own use case:
- HashSet: Use when order is not important and performance is critical.
- LinkedHashSet: Use when you need to maintain insertion order.
- TreeSet: Use when you need sorted elements.