Java TreeSet and HashSet Deep Dive
⏱ Estimated reading time: 2 min
Java provides Set implementations to store unique elements without duplicates. Two commonly used Set classes are HashSet and TreeSet.
1. HashSet
Definition
-
HashSetis a hash table-based implementation of the Set interface. -
Stores unique elements without any guaranteed order.
-
Allows null elements.
Features
-
Does not maintain insertion order.
-
Provides fast insertion, deletion, and lookup (O(1) average).
-
Implements Serializable and Cloneable interfaces.
-
Not synchronized → not thread-safe.
Example:
Output:
2. TreeSet
Definition
-
TreeSetis a Red-Black tree-based implementation of the SortedSet interface. -
Stores unique elements in sorted order (ascending by default).
-
Does not allow null elements.
Features
-
Elements are automatically sorted.
-
Slower than HashSet for insertion and lookup (O(log n)).
-
Implements NavigableSet, allowing operations like
first(),last(),headSet(), andtailSet().
Example:
Output:
3. Comparison: HashSet vs TreeSet
| Feature | HashSet | TreeSet |
|---|---|---|
| Order | No guaranteed order | Sorted (ascending) |
| Implementation | Hash table | Red-Black tree |
| Performance | Fast (O(1) avg) | Slower (O(log n)) |
| Null Element | Allows one null | Not allowed |
| Duplicates | Not allowed | Not allowed |
| Use Case | Fast access, uniqueness | Sorted unique elements |
4. Key Points
-
Set interface → Guarantees no duplicate elements.
-
HashSet → Best for fast access and unordered storage.
-
TreeSet → Best for automatically sorted, unique elements.
-
Both support iteration using for-each loop, Iterator, and enhanced for loop.
5. Conclusion
HashSet and TreeSet are essential for managing unique collections in Java. Choosing between them depends on performance needs and ordering requirements:
-
Use HashSet → For fast, unordered storage
-
Use TreeSet → For sorted, unique storage
Understanding their differences helps design efficient, reliable Java applications.
Register Now
Share this Post
← Back to Tutorials