Java TreeSet and HashSet Deep Dive

📘 Java 👁 47 views 📅 Dec 01, 2025
⏱ Estimated reading time: 2 min

Java provides Set implementations to store unique elements without duplicates. Two commonly used Set classes are HashSet and TreeSet.


1. HashSet

Definition

  • HashSet is a hash table-based implementation of the Set interface.

  • Stores unique elements without any guaranteed order.

  • Allows null elements.

Features

  • Does not maintain insertion order.

  • Provides fast insertion, deletion, and lookup (O(1) average).

  • Implements Serializable and Cloneable interfaces.

  • Not synchronized → not thread-safe.

Example:

import java.util.HashSet; public class Test { public static void main(String[] args) { HashSet set = new HashSet<>(); set.add("Java"); set.add("Python"); set.add("C++"); set.add("Java"); // Duplicate, ignored System.out.println("HashSet: " + set); set.remove("C++"); System.out.println("After removal: " + set); } }

Output:

HashSet: [Java, Python, C++] After removal: [Java, Python]

2. TreeSet

Definition

  • TreeSet is a Red-Black tree-based implementation of the SortedSet interface.

  • Stores unique elements in sorted order (ascending by default).

  • Does not allow null elements.

Features

  • Elements are automatically sorted.

  • Slower than HashSet for insertion and lookup (O(log n)).

  • Implements NavigableSet, allowing operations like first(), last(), headSet(), and tailSet().

Example:

import java.util.TreeSet; public class Test { public static void main(String[] args) { TreeSet set = new TreeSet<>(); set.add("Java"); set.add("Python"); set.add("C++"); System.out.println("TreeSet: " + set); // Sorted order set.remove("Python"); System.out.println("After removal: " + set); System.out.println("First element: " + set.first()); System.out.println("Last element: " + set.last()); } }

Output:

TreeSet: [C++, Java, Python] After removal: [C++, Java] First element: C++ Last element: Java

3. Comparison: HashSet vs TreeSet

FeatureHashSetTreeSet
OrderNo guaranteed orderSorted (ascending)
ImplementationHash tableRed-Black tree
PerformanceFast (O(1) avg)Slower (O(log n))
Null ElementAllows one nullNot allowed
DuplicatesNot allowedNot allowed
Use CaseFast access, uniquenessSorted unique elements

4. Key Points

  • Set interface → Guarantees no duplicate elements.

  • HashSet → Best for fast access and unordered storage.

  • TreeSet → Best for automatically sorted, unique elements.

  • Both support iteration using for-each loop, Iterator, and enhanced for loop.


5. Conclusion

HashSet and TreeSet are essential for managing unique collections in Java. Choosing between them depends on performance needs and ordering requirements:

  • Use HashSet → For fast, unordered storage

  • Use TreeSet → For sorted, unique storage

Understanding their differences helps design efficient, reliable Java applications.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes