---
title: "Explain the difference between TreeSet and HashSet in Java."  
description: "TreeSet and HashSet are two popular implementations of the Set interface in Java, each with distinct characteristics and use cases."  
author: "Ravi Vishwakarma"  
published: 2024-07-19  
updated: 2024-07-19  
canonical: https://www.mindstick.com/blog/304511/explain-the-difference-between-treeset-and-hashset-in-java  
category: "java"  
tags: ["java", "javac"]  
reading_time: 4 minutes  

---

# Explain the difference between TreeSet and HashSet in Java.

`TreeSet` and `HashSet` are two popular implementations of the `Set` interface in Java, each with distinct characteristics and use cases.

#### HashSet

A HashSet is a [collection of items](https://www.mindstick.com/forum/160239/how-to-create-a-razor-view-that-iterates-over-a-collection-of-items-and-displays-them-dynamically) where every item is unique and is found in the `java.util` package. **Java HashSet** class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the hash sets which means that the class does not guarantee the constant [order of elements](https://www.mindstick.com/forum/158799/write-a-rust-function-to-reverse-the-order-of-elements-in-a-vector) over time. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets, which we shall see further in the article.

**O(1) average time** complexity for `add`, `remove`, and `contains` operations, assuming a good hash function and no hash collisions.

#### Java HashSet Features

A few important features of HashSet are mentioned below:

- Implements Set Interface.
- The underlying [data structure](https://www.mindstick.com/blog/11221/simple-way-to-learn-dynamic-data-structure-in-c-language) for HashSet is Hashtable.
- As it implements the Set Interface, [duplicate values](https://www.mindstick.com/forum/157764/how-to-find-duplicate-values-in-a-sql-table) are not allowed.
- Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects are inserted based on their hash code.
- NULL elements are allowed in HashSet.
- HashSet also implements **Serializable** and **Cloneable** interfaces.

## Syntax

```java
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
```

## Example -

```java
// Java program to illustrate the concept of Collection objects storage in a HashSet
import java.io.*;
import java.util.*;

class CollectionObjectStorage {

    public static void main(String[] args)
    {
        // Instantiate an object of HashSet
        HashSet<ArrayList> set = new HashSet<>();

        // create ArrayList list1
        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add(45);

        // create ArrayList list2
        ArrayList<Integer> list2 = new ArrayList<>();
        list2.add(49);

        // Add elements using add method
        list1.add(1);
        list1.add(2);
        list2.add(1);
        list2.add(2);
        set.add(list1);
        set.add(list2);

        // print the set size to understand the
        // internal storage of ArrayList in Set
        System.out.println(set);
    }
}
```

## Output:

```plaintext
[[49, 1, 2], [45, 1, 2]]
```

#### TreeSet

[**Java TreeSet**](https://www.mindstick.com/forum/160952/what-is-the-difference-between-treeset-and-hashset) class implements the Set interface that uses a tree for storage. It inherits the AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in [ascending order](https://www.mindstick.com/forum/157178/how-to-filter-1000-of-student-name-in-php-in-ascending-order).

It is internally backed by a red-black tree (a self-balancing [binary search](https://www.mindstick.com/forum/159485/working-of-a-binary-search-tree-bst-and-what-is-its-time-complexity-for-insertion-and-retrieval) tree). Maintains elements in a sorted (natural or custom) order. Elements are stored in a sorted order, either natural ordering or according to a provided `Comparator`. **O(log n)** time complexity for `add`, `remove`, and `contains` operations due to the tree structure.

## Syntax

```plaintext
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
```

## Example

```java
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        Set<String> treeSet = new TreeSet<>();
        treeSet.add("Apple");
        treeSet.add("Banana");
        treeSet.add("Orange");

        // Elements are in sorted order
        for (String element : treeSet) {
            System.out.println(element);
        }
    }
}
```

## Summary of Differences

| Feature | HashSet | TreeSet |
| --- | --- | --- |
| [Internal Structure](https://answers.mindstick.com/qa/99072/how-the-earth-s-internal-structure-is-being-changed-year-by-year) | Hash table | Red-black tree |
| Ordering | No order | Sorted order |
| Performance | O(1) for basic operations | O(log n) for basic operations |
| Null Handling | Allows one null element | Does not allow null elements |
| Memory Overhead | Lower | Higher |
| Use Cases | Fast access, insertion, deletion | Sorted elements, range operations |

- **HashSet**: Use when you need fast, unordered collection operations and can tolerate occasional hash collisions. Ideal for scenarios where insertion, deletion, and access times need to be minimal, and the order of elements does not matter.
- **TreeSet**: Use when you need a sorted set with guaranteed log(n) time complexity for basic operations. Ideal for scenarios requiring a sorted collection and efficient range of queries or when the natural ordering of elements is crucial.

## Read more

[**Compare ArrayList and LinkedList in Java. When would you use one over the other?**](https://www.mindstick.com/blog/304508/compare-arraylist-and-linkedlist-in-java)

[**What is a HashMap in Java and how does it work internally?**](https://www.mindstick.com/blog/304510/hashmap-in-java-and-how-does-it-work-internally)

---

Original Source: https://www.mindstick.com/blog/304511/explain-the-difference-between-treeset-and-hashset-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
