HashSet vs TreeSet in Java
In this lesson: HashSet vs TreeSet compared — ordering, speed, null handling — with examples and comparison table. In Hindi & English.
Two kinds of Set
HashSet and TreeSet are both Sets — they store only unique items — but the big difference is order. HashSet keeps no order and is faster; TreeSet keeps items automatically sorted but is a little slower. You pick based on whether you need sorting.
HashSet
import java.util.HashSet; HashSet<Integer> set = new HashSet<>(); set.add(30); set.add(10); set.add(20); set.add(10); // duplicate ignored System.out.println(set); // order not guaranteed
HashSet stores unique items with no guaranteed order, which makes it very fast for add, remove and contains. Use it when you only care about uniqueness and speed.
TreeSet
import java.util.TreeSet; TreeSet<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); // sorted automatically
TreeSet keeps items in sorted order automatically. Adding 30, 10, 20 gives them back as 10, 20, 30. It is the choice when you need a set that stays sorted.
Order is the big difference
- HashSet — no order; items may appear in any arrangement.
- TreeSet — natural sorted order (numbers ascending, strings A-Z).
- LinkedHashSet — a third option that keeps insertion order.
If order does not matter, HashSet is best. If you need sorting, use TreeSet.
Performance and nulls
- Speed: HashSet is faster (near constant time); TreeSet is slower (keeps sorting).
- Null: HashSet allows one null; TreeSet allows none (it must compare to sort).
- Requirement: TreeSet elements must be comparable.
Comparison
| Point | HashSet | TreeSet |
|---|---|---|
| Unique items | Yes | Yes |
| Order | None | Sorted |
| Speed | Faster | Slower |
| Null allowed | One | None |
| Best for | Speed, uniqueness | Sorted unique data |
Common mistakes
- Expecting order from HashSet. It has none — use TreeSet or LinkedHashSet.
- Adding null to TreeSet. It throws NullPointerException.
- Using TreeSet when order is not needed. HashSet is faster.
- Non-comparable elements in TreeSet. They must be comparable, or supply a Comparator.
Summary
- Both store only unique items.
- HashSet has no order and is faster.
- TreeSet keeps items sorted but is slower.
- HashSet allows one null; TreeSet allows none.
- Use HashSet for speed, TreeSet for sorted data, LinkedHashSet for insertion order.
Next, revise sets in the Collections Framework, or learn sorting rules with Comparable vs Comparator.
