1. Introduction
In Java, SortedSet and NavigableSet are interfaces that extend the Set interface, which is a collection that contains no duplicate elements. SortedSet provides a total ordering on its elements, whereas NavigableSet further extends SortedSet with additional methods that allow for more precise retrieval operations.
2. Key Points
1. SortedSet offers basic functionality for maintaining a sorted set.
2. NavigableSet includes all the features of SortedSet and adds methods for navigation.
3. NavigableSet provides methods to retrieve elements based on the closest match to a given target value.
4. TreeSet is an example of a class that implements both SortedSet and NavigableSet.
3. Differences
SortedSet | NavigableSet |
---|---|
Provides a set that maintains its elements in a sorted order. | Extends the SortedSet interface to provide additional navigation methods. |
Includes methods like first(), last(), headSet(), tailSet(), and subSet(). | Includes methods like lower(), floor(), ceiling(), higher(), pollFirst(), and pollLast(). |
Does not have methods for close matches or navigation based on a target value. | Provides methods for finding exact or close matches for given search targets. |
4. Example
// Import the necessary classes
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
public class SetComparison {
public static void main(String[] args) {
// Step 1: Create a TreeSet, which is both a NavigableSet and SortedSet
NavigableSet<Integer> navigableSet = new TreeSet<>();
// Step 2: Add elements to the TreeSet
navigableSet.add(1);
navigableSet.add(3);
navigableSet.add(5);
// Step 3: Use NavigableSet methods to navigate the set
System.out.println("First element: " + navigableSet.first());
System.out.println("Last element: " + navigableSet.last());
System.out.println("Lower than 4: " + navigableSet.lower(4));
System.out.println("Floor of 4: " + navigableSet.floor(4));
System.out.println("Ceiling of 4: " + navigableSet.ceiling(4));
System.out.println("Higher than 4: " + navigableSet.higher(4));
}
}
Output:
First element: 1 Last element: 5 Lower than 4: 3 Floor of 4: 3 Ceiling of 4: 5 Higher than 4: 5
Explanation:
1. A TreeSet, which implements both NavigableSet and SortedSet, is created and populated.
2. Elements are added to the set, which are automatically ordered based on their natural ordering.
3. Different methods from the NavigableSet interface are used to find elements relative to the specified target (the number 4), demonstrating how NavigableSet provides precise control over the retrieval of elements.
5. When to use?
- Use SortedSet when you need a set that maintains its elements in sorted order and you only need basic set operations.
- Opt for NavigableSet when you need to perform more complex searches, such as finding the closest matches to a particular element, or when you need to iterate through a subset of a set in reverse order.
Comments
Post a Comment
Leave Comment