Difference between HashSet vs TreeSet in Java

By | 2017-05-27T10:53:36+05:30 May 27th, 2015|java|

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 are implemented classes of 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 when ever 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.

Where as TreeSet stores the elements in natural order. For this TreeSet also we can not expect the insertion order but it will stores 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, where as in TreeSet we can not add only homogeneous elements.

HashSet Example :

Set set = new HashSet();

The above example is possible for HashSet.

TreeSet Example :

Set set = new TreeSet();

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, where as TreeSet doesn’t allow the null values. If 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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment