🌳 vs 🧩 — TreeSet
and HashSet
are both implementations of the Set
interface in Java, but they have very different behaviors under the hood.
Let’s compare them clearly and concisely:
✅ 1. Ordering
Feature | HashSet | TreeSet |
---|
Ordering | ❌ No ordering — elements are unordered | ✅ Sorted according to natural order or a custom Comparator |
Example | [banana, apple, orange] (random) | [apple, banana, orange] (sorted) |
✅ 2. Performance (Time Complexity)
Operation | HashSet (backed by HashMap ) | TreeSet (backed by TreeMap ) |
---|
add , remove , contains | O(1) average case | O(log n) |
HashSet
is faster on average.TreeSet
trades speed for sorted order.
✅ 3. Null elements
Feature | HashSet | TreeSet |
---|
Null allowed? | ✅ Yes (only one null) | ⚠️ Only if null is comparable — otherwise throws NullPointerException |
✅ 4. Underlying data structure
Set Type | Internally uses |
---|
HashSet | HashMap (buckets) |
TreeSet | TreeMap (Red-Black Tree) |
✅ 5. Use case difference
Use Case | Choose… |
---|
Fast insertion/lookup, no order | HashSet |
Keep elements sorted | TreeSet |
Need range queries (e.g. headSet() , tailSet() ) | TreeSet |
🔥 Code Comparison
Set<String> hashSet = new HashSet<>();
hashSet.add("banana");
hashSet.add("apple");
hashSet.add("orange");
System.out.println(hashSet); // Unpredictable order
Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
treeSet.add("orange");
System.out.println(treeSet); // [apple, banana, orange]
🧠 TL;DR
Feature | HashSet | TreeSet |
---|
Order | ❌ None | ✅ Sorted |
Speed | ⚡ Fast (O(1)) | 🕗 Slower (O(log n)) |
Nulls allowed | ✅ One | ⚠️ Careful — may throw |
Backing structure | HashMap | TreeMap |