Difference between Tree Set and Hash Set in Java

JavaObject Oriented ProgrammingProgramming

Hash set and tree set both belong to the collection framework. HashSet is the implementation of the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while HashSet is backed by a hashmap.

Sr. No.KeyHash SetTree Set
1
Implementation 
Hash set is implemented using HashTable 
The tree set is implemented using a tree structure. 
2
Null Object 
HashSet allows a null object 
The tree set does not allow the null object. It throws the null pointer exception. 
3
Methods 
Hash set use equals method to compare two objects 
Tree set use compare method for comparing two objects. 
4
Heterogeneous object 
Hash set doesn't now allow a heterogeneous object 
Tree set allows a heterogeneous object 
5
Ordering 
HashSet does not maintain any order 
TreeSet maintains an object in sorted order 

Example of TreeSet

class TreeSetExmaple {
   public static void main(String[] args){
      TreeSet<String> treeset = new TreeSet<String>();
      treeset.add("Good");
      treeset.add("For");
      treeset.add("Health");
      //Add Duplicate Element
      treeset.add("Good");
      System.out.println("TreeSet : ");
      for (String temp : treeset) {
         System.out.println(temp);
      }
   }
}

Output

TreeSet:
   For
   Good
   Health

Example of HashSet

class HashSetExample {
   public static void main(String[] args){
      HashSet<String> hashSet = new HashSet<String>();
      hashSet.add("Good");
      hashSet.add("For");
      hashSet.add("Health");
      //Add Duplicate Element
      hashSet.add("Good");
      System.out.println("HashSet: ");
      for (String temp : hashSet) {
         System.out.println(temp);
      }
   }
}

Output

HashSet:
   Health
   For
   Good

raja
Published on 18-Nov-2019 06:33:52
Advertisements