What is the Difference Between HashSet and TreeSet in Java?
Both implement Set interface (no duplicates), but differ in ordering, performance, and null handling.
1. HashSet (Hash Table)
import java.util.*;
public class HashSetExample {
public static void main(String[] args) {
Set hashSet = new HashSet<>();
hashSet.add("Banana");
hashSet.add("Apple");
hashSet.add("Cherry");
hashSet.add("Apple"); // Duplicate - ignored
System.out.println("HashSet (no order): " + hashSet);
// Output order may vary (depends on hash codes)
// O(1) operations
System.out.println("Contains Apple? " + hashSet.contains("Apple"));
System.out.println("Size: " + hashSet.size());
// Allows one null
hashSet.add(null);
System.out.println("With null: " + hashSet);
// Remove element
hashSet.remove("Banana");
System.out.println("After removal: " + hashSet);
// Iteration
for (String item : hashSet) {
System.out.println(item);
}
}
}
2. TreeSet (Red-Black Tree)
public class TreeSetExample {
public static void main(String[] args) {
Set treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
treeSet.add("Date");
// Automatically sorted
System.out.println("TreeSet (sorted): " + treeSet);
// Output: [Apple, Banana, Cherry, Date]
// O(log n) operations
System.out.println("First: " + ((TreeSet) treeSet).first());
System.out.println("Last: " + ((TreeSet) treeSet).last());
// Navigation methods
System.out.println("Lower than Cherry: " + ((TreeSet) treeSet).lower("Cherry"));
System.out.println("Higher than Banana: " + ((TreeSet) treeSet).higher("Banana"));
// Subset views
SortedSet subSet = ((TreeSet) treeSet).subSet("Banana", "Date");
System.out.println("Subset: " + subSet);
// No null allowed (throws NullPointerException)
// treeSet.add(null); // ERROR!
}
}
Custom Objects in TreeSet
class Student implements Comparable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return id + ":" + name;
}
}
public class CustomTreeSet {
public static void main(String[] args) {
Set students = new TreeSet<>();
students.add(new Student(103, "Charlie"));
students.add(new Student(101, "Alice"));
students.add(new Student(102, "Bob"));
System.out.println("Sorted by ID: " + students);
// Output: [101:Alice, 102:Bob, 103:Charlie]
// Using Comparator
Set byNameSet = new TreeSet<>(Comparator.comparing(s -> s.name));
byNameSet.add(new Student(103, "Charlie"));
byNameSet.add(new Student(101, "Alice"));
byNameSet.add(new Student(102, "Bob"));
System.out.println("Sorted by name: " + byNameSet);
}
}
Performance Test
public class SetPerformanceTest {
public static void main(String[] args) {
int size = 100000;
// HashSet test
Set hashSet = new HashSet<>();
long start = System.nanoTime();
for (int i = 0; i < size; i++) hashSet.add(i);
long hashAdd = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < size; i++) hashSet.contains(i);
long hashContains = System.nanoTime() - start;
// TreeSet test
Set treeSet = new TreeSet<>();
start = System.nanoTime();
for (int i = 0; i < size; i++) treeSet.add(i);
long treeAdd = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < size; i++) treeSet.contains(i);
long treeContains = System.nanoTime() - start;
System.out.println("HashSet add: " + hashAdd/1_000_000 + "ms");
System.out.println("TreeSet add: " + treeAdd/1_000_000 + "ms");
System.out.println("HashSet contains: " + hashContains/1_000_000 + "ms");
System.out.println("TreeSet contains: " + treeContains/1_000_000 + "ms");
// HashSet is significantly faster
}
}
Comparison Table
| Feature | HashSet | TreeSet |
|---|---|---|
| Ordering | No order (arbitrary) | Sorted (natural/comparator) |
| Performance | O(1) add/remove/contains | O(log n) add/remove/contains |
| Null values | Allows one null | No null allowed |
| Memory | Less overhead | More overhead (tree structure) |
| When to use | Fast lookups, order not important | Sorted data, range queries |
Master Java Collections with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
