Sets in Java
HashSet vs TreeSet in Java
In Java, both HashSet
and TreeSet
implement the Set
interface, which represents a collection of unique elements (no duplicates). However, they differ in ordering, performance, and internal implementation.
🔹 1. HashSet
✅ Characteristics:
- Backed by a hash table
- Does not maintain any order of elements
- Allows
null
elements (only one)
📌 Example:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate - ignored
System.out.println(fruits); // Order is not guaranteed
}
}
🚀 Performance:
Operation | Time Complexity |
---|---|
add() | O(1) average |
remove() | O(1) average |
contains() | O(1) average |
✅ Use Case:
- When fast lookups, insertions, and deletions are needed
- Ordering is not important
🔹 2. TreeSet
✅ Characteristics:
- Backed by a Red-Black Tree (self-balancing binary search tree)
- Sorted in natural order (or by a custom comparator)
- Does not allow
null
elements (throwsNullPointerException
)
📌 Example:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> fruits = new TreeSet<>();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Cherry");
System.out.println(fruits); // Output: [Apple, Banana, Cherry]
}
}
🚀 Performance:
Operation | Time Complexity |
---|---|
add() | O(log n) |
remove() | O(log n) |
contains() | O(log n) |
✅ Use Case:
- When you need sorted data or need to perform range queries
- Order is important
✅ Summary
Feature | HashSet | TreeSet |
---|---|---|
Underlying Structure | Hash table | Red-Black Tree |
Order | No order | Sorted (natural or custom) |
Null Elements | Allowed (one) | Not allowed |
Performance | Faster (O(1) avg ops) | Slower (O(log n)) |
Allows Duplicates | ❌ | ❌ |
Thread-safe | ❌ (use Collections.synchronizedSet() ) |
❌ |