In this tutorials, we are going to understand what is the differences between HashSet vs TreeSet in Java.
HashSet vs TreeSet :
Both HashSet and TreeSet have implemented classes of the Set interface. Though these two are implementations of Set interface we can see some significant differences between HashSet and TreeSet.
Recommended: What is HashSet in Java
1) Insertion Order :
HashSet doesn’t maintain the insertion order. That means whenever we add elements into HashSet we can not expect to get the elements while iterating as inserted order. It will add the elements in random order.
Whereas TreeSet stores the elements in the natural order. For this TreeSet also we can not expect the insertion order but it will store as per the default order.
Default Order: In case of number the default order is ascending and in case of strings the default order is alphabetical.
If we want to change the default order with TreeSet, we can customise it using TreeSet with Comparator.
2) Homogeneous Elements :
In HashSet, we can store homogeneous elements, whereas in TreeSet we can not add only homogeneous elements.
HashSet Example :
Set set = new HashSet(); set.add("A"); set.add("M"); set.add("b"); set.add(4); set.add(1); set.add(9);
The above example is possible for HashSet.
TreeSet Example :
Set set = new TreeSet(); set.add("A"); set.add("M"); set.add("b"); set.add(4); set.add(1); set.add(9);
But in tree set we can not store String and Integers at a time. It will throw java.lang.ClassCastException.
3) Allow Null Values :
HashSet allows the null values, whereas TreeSet doesn’t allow the null values. If you try to store the null value to TreeSet it will throw NullPointerException.
4) Speen & Performance :
Comparatively HashSet much faster then the TreeSet.
5) Implementations :
Comparing with the HashSet, TreeSet having much implementation methods with helps us to iterate the collection efficiently. Like pollFirst(),pollLast(),first(),last(),ceiling(),lower() and more..
Happy Learning 🙂