Last Updated on July 6, 2022 by Ria Pathak
Introduction
We all have been using HashSet, LinkedHashSet, and TreeSet in Java. But do you know what are the differences between them and how they all are similar too in some ways?
To gain more knowledge about these data structures, let’s discuss their differences and similarities below.
Differences:
Discussion Point | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Data Structure used internally | Uses HashMap | Uses LinkedHashMap | Uses TreeMap |
Order if elements | Doesn’t maintain the order of insertion and stores unique elements | Maintains insertion order of elements | Stores elements in sorted order (ascending by default), which can be defined using a custom comparator. |
Time complexity of operations | Takes O(1) for insertion, updating, and deletion | Takes O(1) for insertion, updating, and deletion | Takes O(log(n)) for insertion, updating and deletion |
Null value handling | Allows only one null value | Allows only one null value | Doesn’t allow null value. Will throw NullPointerException upon insertion of null value. |
How to use (syntax) | HashSet a = new HashSet(); | LinkedHashSet a = new LinkedHashSet(); | TreeSet a = new TreeSet(); |
Performance | Has better performance when compared to LinkedHashSet and TreeSet. | Performs slower than TreeSet. And almost similar to HashSet but slower because it internally maintains LinkedList to maintain the insertion order of elements. | Performs better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and removal operation. |
Similarities:
- HashSet, LinkedHashSet, and TreeSet all are designed to store unique elements i.e, they can’t store duplicate elements even if duplicates are inserted into them.
- These three are clonable and serializable.
- To use them in a multi-threading environment we need to make them externally synchronized as both LinkedHashSet and TreeSet are not thread-safe.
I hope now you understand the difference and similarities between HashSet, LinkedHashSet, and TreeSet in Java. These things are necessary to be kept in mind while using them. To practice more problems you can check out MYCODE | Competitive Programming.