![]() |
VOOZH | about |
In Java, HashSet, LinkedHashSet, and TreeSet are implementations of the Set interface, which store unique elements only. While all three prevent duplicate entries, they differ in ordering, internal data structure, and performance.
HashSet stores unique elements without maintaining any insertion or sorting order. It internally uses a hash table, which makes it very fast for basic operations like add, remove, and search. HashSet allows one null element.
[20, 10, 30]
Explanation: The output order is not predictable because HashSet does not preserve insertion order or sorting. Duplicate value 10 is ignored since sets allow only unique elements.
LinkedHashSet stores unique elements while preserving the order in which they were inserted. It uses a hash table along with a doubly linked list, making it slightly slower than HashSet but useful when order matters. It also allows one null element.
[Java, Python, C++]
Explanation: Elements are printed in the same order in which they were added to the set. This happens because LinkedHashSet maintains insertion order internally.
TreeSet stores unique elements in sorted order, either by natural ordering or by a custom comparator. It internally uses a Red-Black Tree, which results in slower performance compared to HashSet and LinkedHashSet. TreeSet does not allow null elements.
[10, 30, 40]
Explanation: Even though elements are inserted in random order, TreeSet automatically sorts them in ascending order using natural ordering.
All implement the Set interface, so no duplicate elements are allowed. Provide common methods: add(), remove(), contains(), size().
Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
Internal Working | Uses HashMap internally | Uses LinkedHashMap internally | Uses TreeMap internally |
Order | No insertion order | Maintains insertion order | Elements sorted by Comparator or natural order |
Time Complexity | O(1) for insert, remove, retrieve | O(1) (slightly slower due to linked list maintenance) | O(log n) for insert, remove, retrieve |
Performance | Fastest | Slightly slower than HashSet | Slower for insertion/removal due to sorting |
Comparison | Uses hashCode() and equals() | Uses hashCode() and equals() | Uses compare() and compareTo() |
Null Elements | Allows 1 null | Allows 1 null | Not allowed |
Use Case | Store unique elements, order not important | Store unique elements, maintain insertion order | Store unique elements in sorted order |
Syntax | HashSet<Type> obj = new HashSet<>(); | LinkedHashSet<Type> obj = new LinkedHashSet<>(); | TreeSet<Type> obj = new TreeSet<>(); |