🔍 Comparison: HashSet vs LinkedHashSet vs TreeSet
Feature | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Ordering | ❌ Unordered | ✔ Maintains Insertion order | ✔ Sorted (natural order) |
Duplicates | ❌ Not allowed | ❌ Not allowed | ❌ Not allowed |
Nulls | ✔ Allow one null | ✔ Allow one null element | ⚠ Allows one null only if it's the first inserted and no comparator is used (Java 8 and below). In newer versions, |
Performance | ✔ Fastest (O(1)) | ⚠ Slightly slower than HashSet | ❌ Slowest (O(log n) due to sorting) |
Internal | Hash Table | Hash Table + Linked List | Red-Black Tree (self-balancing BST) |
Implementation | Set |
Set |
Set , SortedSet , NavigableSet |
Use Case | Best for fast access | Best when you want to preserve | Best when you need sorted elements |
✔ HashSet Example (No Order)
Set<String> hashSet = new HashSet<>();
hashSet.add("banana");
hashSet.add("apple");
hashSet.add("cherry");
System.out.println(hashSet); // Order is NOT guaranteed
✔ LinkedHashSet Example (Insertion Order)
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("banana");
linkedHashSet.add("apple");
linkedHashSet.add("cherry");
System.out.println(linkedHashSet); // Output: [banana, apple, cherry]
✔ TreeSet Example (Sorted Order)
Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
treeSet.add("cherry");
System.out.println(treeSet); // Output: [apple, banana, cherry]