Java Reference
In-Depth Information
null
Lo
Ken
Ellen
Navigable Set
A navigable set is a specialized type sorted set that lets you work with its subsets in a variety of ways. An instance of the
NavigableSet represents a navigable set. The NavigableSet interface inherits from the SortedSet interface and defines
some additional methods to extend the functionality provided by the SortedSet . It extends SortedSet in four ways:
It lets you navigate the set in reverse order. The reverse order is the opposite order in
which your SortedSet would be sorted normally. Its descendingSet() method returns a
NavigableSet object, which is another view of the same NavigableSet in the reverse order.
If you modify the original NavigableSet or the one returned from the descendingSet()
method, the modifications will be reflected in both sets.
headSet() , tailSet() , and subSet() in
SortedSet , which accept a boolean flag to include the element at the beginning or the end of
the subset boundary.
It provides four methods, lower() , floor() , higher() , and ceiling() , that are used to search for an element
based on search criteria. The lower() method returns the greatest element in the NavigableSet that is less than the
specified element. The floor() method is similar to the lower() method that returns the greatest element in the
NavigableSet that is less than or equal to the specified element. The higher() method returns the least element in
the NavigableSet that is greater than the specified element. The ceiling() method is similar to the higher() method
that returns the least element in the NavigableSet that is greater than or equal to a specified element.
It provides two methods, pollFirst() and pollLast() , that retrieve and remove the first and the last element of
the NavigableSet , respectively. If the NavigableSet is empty, they return null .
The TreeSet class is one of the implementation classes for the NavigableSet interface. Since a NavigableSet is
also a SortedSet and a SortedSet is also a Set , you can use an object of TreeSet as a set, a sorted set, and a navigable
set. If you do not need ordering of the elements in a set, you are better off using the HashSet implementation class
rather than the TreeSet implementation class.
Listing 12-12 demonstrates how to use navigable sets. It uses integers as the elements of the NavigableSet
because numbers seem to be more intuitive when you perform methods like higher() and lower() . The output
shows how a NavigableSet performs all its operations on its elements.
It adds another version of the three methods
Listing 12-12. Using a NavigableSet to Get a Subset of a Set
// NavigableSetTest.java
package com.jdojo.collections;
import java.util.TreeSet;
import java.util.NavigableSet;
public class NavigableSetTest {
public static void main(String[] args) {
// Create a navigable set and add some integers
NavigableSet<Integer> ns = new TreeSet<>();
ns.add(1);
ns.add(2);
 
Search WWH ::




Custom Search