English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The Difference Between TreeSet and HashSet in Java

Both HashSet and TreeSet belong to the collection framework. HashSet is an implementation of the Set interface, while TreeSet implements a sorted set. TreeSet is supported by TreeMap, while HashSet is supported by HashMap.

IndexKeyHashSetTreeSet
1
Implementation 
HashSet is implemented using HashTable 
TreeSet is implemented using a tree structure. 
2
Null Object 
HashSet allows one null object 
TreeSet does not allow null objects. It throws a NullPointerException. 
3
Method 
HashSet compares two objects using the equals method 
TreeSet compares two objects using the comparison method. 
4
Heterogeneous Objects 
HashSet now does not allow heterogeneous objects 
TreeSet allows heterogeneous objects 
5
Order 
HashSet does not maintain any order 
TreeSet maintains the sorted order of objects 

TreeSet Example

class TreeSetExample {
   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 Result

TreeSet:
   Health
   For
   Good

HashSet Example

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 Result

TreeSet:
   Health
   Good
   For