Differences between HashSet and TreeSet in Java

Hello Learners, today we are going to learn about the differences between HashSet and TreeSet in Java. The HashSet and TreeSet both the classes implements Set interface under Java.util package. So there are some similarities as well as some differences. Let’s see the points below to get you an idea of it.

HashSet Class

  1. HashSet extends AbstractSet class and implements NavigableSet interface.
  2. It internally uses a Hash Table.
  3. Stores the data in order they were inserted i.e. unordered.
  4. Insertion, deletion etc such operations are faster in a HashSet.
  5. HashSet allows null values but with some restrictions. You can add only One value in your HashSet, not more than that.
  6. It has equal() and hashcode() methods to compare the elements within the set.
  7. HashSet doesn’t have any of its own member function or instances, instead it uses the methods from parent class.

TreeSet Class

  1. TreeSet extends AbstractSet class and implements NavigableSet interface.
  2. It internally uses a tree data structure.
  3. The main benefit of TreeSet is that it stores the data in a sorted manner.
  4. TreeSet is slower than HashSet in insertion, deletion etc. because it traverses the whole tree i.e. all the elements inside the TreeSet before performing any operation.
  5. TreeSet doesn’t allow you to add null values in the set at all and throws NullPointerException error.
  6. It doesn’t use equal() and hashcode() method. Instead we can implement Comparator interface to use compare() and compareTo() method.
  7. TreeSet has its own methods like pollFirst(), pollLast(), ceiling(), first(), last() etc which increases its functionality.

Now let’s see an example for better understanding.

import java.util.Collections;
import java.util.HashSet;
import java.util.TreeSet;

public class setDemo {
  public static void main(String[] args) {
    
    HashSet<Integer> hs = new HashSet<Integer>();
    TreeSet<Integer> ts = new TreeSet<Integer>();
    Collections.addAll(hs,3,5,2,8,1,9,7);
    Collections.addAll(ts,3,5,2,8,1,9,7);
    System.out.println("elements of hashset are: "+hs);
    System.out.println("elements of treeset are :"+ts);
  }
}

OUTPUT:

elements of hashset are: [1, 2, 3, 5, 7, 8, 9]
elements of treeset are :[1, 2, 3, 5, 7, 8, 9]

Point To Remember: HashSet and TreeSet both are non-synchronized. This means that other threads can modify the set while execution. They aren’t thread-safe but we can do it explicitly.

make a Set synchronized --> Set<datatype> s = Collections.synchronizedSet(setobject);

To learn more about the Java HashMaps and HashTables click here. So, that’s all for now about the differences between HashSet and TreeSet in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *