Difference between hashset and treeset in java

Let’s learn difference between hashset and treeset in java.

Difference between hashset and treeset in java

HashSetTreeSet
hashset do not maintain any order.sorted according to natural order. If not use compareTo() method.
uses equals() method for comparison.uses compareTo() method for ordering two objects.
hashset is implemented using HashTable.TreeSet is implemented using Tree structure.
hashset allows a null object.treeset do not allow null object. It throws NullPointerException.
hashset do not allow heterogeneous object.TreeSet allow heterogeneous object.

treeset vs hashset example:

// hashset example
import java.util.HashSet;
public class HashSetExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("hello");
      hs.add("world");
      hs.add("core");
      hs.add("java");
      // duplicate elements are removed
      hs.add("hello");
      // printing HashSet elements
      System.out.println("HashSet elements: ");
      for(String str : hs)
      {
         System.out.println(str);
      }
   }
}


Output:

HashSet elements:
core
world
java
hello


// treeset example
import java.util.TreeSet;
public class TreeSetDemo
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("hello");
      ts.add("world");
      ts.add("core");
      ts.add("java");
      // duplicate elements are removed
      ts.add("hello");
      // printing TreeSet elements
      System.out.println("TreeSet elements: ");
      for(String str : ts)
      {
         System.out.println(str);
      }
   }
}


Output:

TreeSet elements:
core
hello
java
world


Also read – major features of java