Difference between HashSet and TreeSet

HashSet and TreeSet, both are used to store unique elements. Because both do not allow duplicate elements. There are a lot of similarities because both implements Set interface. But there is some unique difference between them. In this post, we will discuss the difference between HashSet and TreeSet. If you are not familiar with internal working of HashSet and the internal working of TreeSet then you should read them first. Each one is used for different purposes and in different scenarios.

Difference between HashSet and TreeSet
  1. HashSet doesn’t maintain the order of elements because it doesn’t use any criteria to sort the elements in any order. All the elements are placed in random order.
    TreeSet maintains the natural order of the element by default. It internally uses a comparable or comparator to sort the elements.
  2. We can’t sort the elements in HashSet, because it is an unordered collection. There is no method provided that can sort the element.
    TreeSet we can sort the elements based on the requirement. If we are not providing any comparator to TreeSet, it automatically sorts the element ascending order. We can sort the element by the custom comparator.
  3. A HashSet allows only one null because it internally uses the HashMap and HashMap allows only a unique key.
    TreeSet doesn’t allow null, because it internally uses the compareTo() methods to compare the values of TreeSet. TreeSet throws NullPointerException if we try to add null in TreeSet.
  4. HashSet is faster than TreeSet and should be the preferred choice if the sorting of the element is not required.
  5. HashSet uses equals() method to compare the elements of HashSet and detect the duplicates elements while TreeSet uses the compareTo() method for the same purpose.
  6. HashSet internally uses the HashMap while TreeSet uses the TreeMap.
  7. If you want to store only unique elements then HashSet is a good choice but if you want to sort the elements as well then you should use TreeSet.

Leave a Comment