HashSet vs TreeSet: Java provides several collection classes to manage groups of objects efficiently. Two commonly used classes for managing sets of elements are HashSet
and TreeSet
.
HashSet vs TreeSet in Java
HashSet
HashSet
is a collection class in Java that implements the Set interface. It uses a hash table to store elements and does not allow duplicate values. HashSet does not guarantee the order of elements.
HashSet: Unordered and Unique
The HashSet
class is like a magical bag where you can throw in items, and it ensures that you don’t have duplicates. However, the order in which you put things into the bag doesn’t guarantee the order in which you’ll take them out. Let’s look at a simple example:
HashSet Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Creating a HashSet
HashSet hashSet = new HashSet<>();
// Adding elements to the HashSet
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Grapes");
hashSet.add("Apple"); // Duplicate elements are not allowed
// Displaying the elements of HashSet
System.out.println("HashSet: " + hashSet);
}
}
In this example, a HashSet is created to store strings. The HashSet does not allow duplicate elements, so when trying to add “Apple” again, it will not be added.
Read also: Best 50 Java Multiple-Choice Questions to Test Your Skills, and Boost Your Knowledge
TreeSet
TreeSet
is another collection class in Java that implements the Set interface. It stores elements in a sorted order (ascending by default) using a red-black tree. TreeSet does not allow duplicate elements.
TreeSet: Sorted and Unique
On the other hand, TreeSet
is like a neatly organized shelf where items are not unique but also arranged in a specific order. This order is determined by the natural ordering of the elements or by a specified comparator. Let’s see how it works:
TreeSet Example:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Creating a TreeSet
TreeSet treeSet = new TreeSet<>();
// Adding elements to the TreeSet
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Grapes");
treeSet.add("Apple"); // Duplicate elements are not allowed
// Displaying the elements of TreeSet (naturally ordered)
System.out.println("TreeSet (Ordered): " + treeSet);
// Displaying the elements of TreeSet in reverse order
System.out.println("TreeSet (Reverse Ordered): " + treeSet.descendingSet());
}
}
In this example, a TreeSet is created to store strings. TreeSet is automatically ordered, so the elements will be displayed in their natural order. Additionally, we used descendingSet()
to display the elements in reverse order.
Read also: The Best 50 Java Interview Questions with Answers
Difference between HashSet vs TreeSet
Underlying Data Structure:
- HashSet: Backed by a hash table, offering fast insertion and lookup based on hashing.
- TreeSet: Backed by a red-black tree, providing an ordered list of elements and efficient retrieval in sorted order.
Order of Elements:
- HashSet: Elements are unordered and appear in no specific order.
- TreeSet: Elements are sorted in ascending order by their natural ordering or a custom comparator.
Null Values:
- HashSet: Allows null values.
TreeSet: This does not allow null values.
HashSet vs TreeSet Complexity
Operation | HashSet | TreeSet |
add | O(1) on average | O(log n) |
remove | O(1) on average | O(log n) |
contains | O(1) on average | O(log n) |
iteration | O(n) | O(n) |
Example of HashSet vs TreeSet
Imagine storing student names in a set.
- HashSet: You can quickly add and check if a student exists, but you don’t know their order.
- TreeSet: Students are automatically sorted alphabetically, making it easy to iterate through the list or find specific names.
When to use:
- HashSet: Choose when fast insertion and lookup are crucial, and order doesn’t matter.
- TreeSet: Utilize when element order is critical for efficient sorting, searching, or iteration.
// HashSet example
Set<String> hashSet = new HashSet<>();
hashSet.add(“Apple”);
hashSet.add(“Banana”);
hashSet.add(“Orange”);
hashSet.add(“Apple”); // Duplicate, not allowed
System.out.println(“HashSet: ” + hashSet);
// TreeSet example
Set<String> treeSet = new TreeSet<>();
treeSet.add(“Apple”);
treeSet.add(“Banana”);
treeSet.add(“Orange”);
// treeSet.add(null); // Uncommenting this line will throw a NullPointerException
System.out.println(“TreeSet: ” + treeSet);
Feature | HashSet | TreeSet |
Ordering | Unordered | Ordered (ascending) |
Underlying Data Structure | Hash Table | Red-Black Tree |
Null Values | Allowed | Not Allowed |
Complexity (lookup/insertion/deletion) | O(1) | O(log n) |
Example | Unorganized collection of music albums | Organized collection of music albums by name |
Use Cases | Fast access, frequent modification, order doesn’t matter | Ordered data access, range queries |