Difference Between TreeSet and HashSet in Java



In Java, HashSet and TreeSet both belong to the collection framework. HashSet is the implementation of the Set interface, whereas TreeSet implements a sorted set. TreeSet is backed by TreeMap while HashSet is backed by a HashMap.

Difference Table

The following are the key differences between HashSet and TreeSet :

Sr. No. Key Hash Set Tree 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 

TreeSet

Syntax

The Following is the syntax of TreeSet :

TreeSet<String> treeset = new TreeSet<String>();

Example

Below is an example of a TreeSet in Java :

import java.util.TreeSet; 
public 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

Time complexity: O(log n), due to Red-Black Tree operations.
Space complexity: O(n), stores elements in a balanced tree structure.

HashSet

Syntax

The Following is the syntax of HashSet :

HashSet<String> hashSet = new HashSet<String>();

Example

Below is an example of a HashSet in Java :

import java.util.HashSet; 
public 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

Time complexity: O(n), due to hash collisions.
Space complexity: O(n), stores elements in a Hash Table.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-04-14T12:15:27+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements