Java provides Set implementations to store unique elements without duplicates. Two commonly used Set classes are HashSet and TreeSet.
HashSet is a hash table-based implementation of the Set interface.
Stores unique elements without any guaranteed order.
Allows null elements.
Does not maintain insertion order.
Provides fast insertion, deletion, and lookup (O(1) average).
Implements Serializable and Cloneable interfaces.
Not synchronized → not thread-safe.
Output:
TreeSet is a Red-Black tree-based implementation of the SortedSet interface.
Stores unique elements in sorted order (ascending by default).
Does not allow null elements.
Elements are automatically sorted.
Slower than HashSet for insertion and lookup (O(log n)).
Implements NavigableSet, allowing operations like first(), last(), headSet(), and tailSet().
Output:
| 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 |
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.
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now