Java Reference
In-Depth Information
The NavigableSet Interface
A TreeSet object has a specifi c ordering, and the TreeSet class implements the
NavigableSet interface, which declares methods for navigating and searching a set.
The interface contains the following generic methods, where E represents the data type of
the elements in the set:
Iterator<E> iterator() returns an iterator in ascending order.
Iterator<E> descendingIterator() returns an iterator in descending order.
E lower(E e) returns the greatest element in this set strictly less than the given
element.
E floor(E e) returns the greatest element in this set less than or equal to the given
element.
E ceiling(E e) returns the least element in this set greater than or equal to the
given element.
E higher(E e) returns the least element in this set strictly greater than the given
element.
NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toEle-
ment, boolean toInclusive) returns a view of the portion of this set whose
elements range from fromElement to toElement .
The interface also defi nes headSet and tailSet methods for retrieving subsets from the
beginning or end of the set.
Let's look at an example. The following code adds a collection of Integer objects to a
TreeSet named tree :
TreeSet<Integer> tree = new TreeSet<Integer>();
for(int i = 1; i <= 20; i++ ) {
tree.add(i);
}
The tree contains 20 Integer objects whose values are 1 to 20. The following statements
demonstrate some of the methods in NavigableSet . Study the code and see if you can
determine its output:
12. Integer ceiling = tree.ceiling(10);
13. System.out.println(“ceiling of 10 = “ + ceiling);
14. Integer higher = tree.higher(10);
15. System.out.println(“floor of 10 = “ + higher);
Search WWH ::




Custom Search