TreeSet and its features
A TreeSet in Java is an implementation of the SortedSet interface, which is part of the Java Collections Framework. It maintains its elements in sorted order, either according to their natural ordering or based on a custom comparator provided at the time of creation. TreeSet does not allow duplicate elements and offers guaranteed log(n) time complexity for basic operations like add, remove, and contains.
Table of Contents
Features of TreeSet:
- 1. Sorted Order: TreeSet maintains its elements in sorted order. The order can be either the natural ordering of the elements or based on a custom comparator provided by the user.
- 2. No Duplicates: TreeSet does not allow duplicate elements. If an attempt is made to add a duplicate element, it will be ignored, as the element is not added again.
- 3. Fast Lookup: TreeSet provides fast lookup operations. The contains() method allows you to quickly check whether a specific element is present in the set.
- 4. Logarithmic Time Complexity: TreeSet offers guaranteed log(n) time complexity for basic operations like add, remove, and contains. This makes it efficient for large sets.
- 5. Backed by Red-Black Tree: Internally, TreeSet is implemented using a red-black tree data structure, which ensures that elements are stored in sorted order while maintaining balance in the tree.
- 6. Null Elements: TreeSet does not allow null elements. If an attempt is made to add a null element, it will throw a NullPointerException.
Example Usage of TreeSet
```java
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet
Set<Integer> treeSet = new TreeSet<>();
// Add elements to the TreeSet
treeSet.add(5);
treeSet.add(2);
treeSet.add(8);
// Adding a duplicate element (ignored)
treeSet.add(5);
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
// Check if an element is present
System.out.println("Contains 2? " + treeSet.contains(2));
// Remove an element
treeSet.remove(8);
System.out.println("TreeSet after removing 8: " + treeSet);
}
}
```
In this example:
- We create a TreeSet of integers and add some elements to it.
- The duplicate element “5” is not added to the set because TreeSet does not allow duplicates.
- We print the contents of the TreeSet and demonstrate the contains and remove operations.
TreeSet is commonly used in scenarios where elements need to be maintained in sorted order, or when efficient range queries are required. It provides fast lookup operations and is suitable for situations where a sorted set of unique elements is needed.