Difference between HashSet and TreeSet in Java

Both HashSets and TreeSets are sets. They do not allow duplicates. Both are not thread-safe. However, since both of them are separate classes in Java, following is a list of differences between them:

HashSet TreeSet
HashSet is implemented using HashTable. TreeSet is implemented using a tree structure.
HashSet methods add, remove, and contains have constant time complexity O(1). In TreeSet the elements are sorted, but the add, remove, and contains methods has time complexity O(log (n)).
Null Object: HashSet allows a null object. The TreeSet does not allow the null object. It throws the null pointer exception.
Methods: HashSet use equals method to compare two objects. TreeSet use compare method for comparing two objects.
Heterogeneous object: HashSet doesn't now allow a heterogeneous object TreeSet allows a heterogeneous object.
Ordering: HashSet does not maintain any order. TreeSet maintains objects in sorted order.

Sample Java code to demonstrate HashSet and TreeSet

public class HashSetAndTreeSet {
    static public void main(String[] args) {
        HashSet<String> hashSet = new HashSet<String>(); 
 
        // add elements to HashSet 
        hashSet.add("Sachin"); 
        hashSet.add("Virat"); 
        hashSet.add("Chahal"); 
        hashSet.add("Rohit"); 
 
        // Duplicate 
        hashSet.add("Virat"); 
 
        // Displaying Hashset elements 
        System.out.println("Hashset contains: "); 
        for (String temp : hashSet) { 
            System.out.println(temp); 
        } 
 
        TreeSet<String> treeSet = new TreeSet<String>(); 
 
        // add elements to HashSet 
        treeSet.add("Sachin"); 
        treeSet.add("Virat"); 
        treeSet.add("Chahal"); 
        treeSet.add("Rohit"); 
 
        // Duplicate 
        treeSet.add("Virat"); 
 
        // Displaying TreeSet elements 
        System.out.println("TreeSet contains: "); 
        for (String temp : treeSet) { 
            System.out.println(temp); 
        }
    }
}

Hope you have enjoyed reading Difference between HashSet and TreeSet in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.