15.5 Sorted Sets and Navigable Sets

Before reading this subsection, it is a good idea to review the Comparable<E> interface (§14.4, p. 761) for defining the natural ordering for objects, and the Comparator<E> interface (§14.5, p. 769) for defining a particular total ordering for objects.

The SortedSet<E> Interface

The SortedSet<E> interface extends the Set<E> interface to provide the functionality for handling sorted sets. Since the elements are sorted, iterating over the set using either the for(:) loop or an iterator will access the elements according to the ordering used by the set.

// First-last elements
E first()
E last()

The first() method returns the first element currently in this sorted set, and the last() method returns the last element currently in this sorted set. The elements are chosen based on the ordering used by the sorted set. Both throw a NoSuchElementException if the sorted set is empty.

Click here to view code image

// Range-view operations
SortedSet<E> headSet(<E> toElement)
SortedSet<E> tailSet(<E> fromElement)
SortedSet<E> subSet(<E> fromElement, <E> toElement)

The headSet() method returns a view of a portion of this sorted set, whose elements are strictly less than the specified element. Similarly, the tailSet() method returns a view of the portion of this sorted set, whose elements are greater than or equal to the specified element. The subSet() method returns a view of the portion of this sorted set, whose elements range from fromElement, inclusive, to toElement, exclusive (also called half-open interval). It throws an IllegalArgumentException if the fromElement is greater than the toElement.

Note that the views present the elements sorted in the same order as the underlying sorted set. Also, changes made through views are reflected in the underlying sorted set, and vice versa.

Click here to view code image

// Comparator access
Comparator<? super E> comparator()

Returns the comparator associated with this sorted set, or null if it uses the natural ordering of its elements. This comparator, if defined, is used by default when a sorted set is constructed, and used when copying elements into new sorted sets.

Leave a Reply

Your email address will not be published. Required fields are marked *