Start of Tutorial > Start of Trail > Start of Lesson | Search |
ASortedSet
is aSet
that maintains its elements in ascending order, sorted according to the elements' natural order, or according to aComparator
provided atSortedSet
creation time. (Natural order andComparator
s are discussed in the previous section, on Object Ordering.) In addition to the normalSet
operations, theSet
interface provides operations for:The
- Range-view: Performs arbitrary range operations on the sorted set.
- Endpoints: Returns the first or last element in the sorted set.
- Comparator access: Returns the
Comparator
used to sort the set (if any).SortedSet
interface is shown below:public interface SortedSet extends Set { // Range-view SortedSet subSet(Object fromElement, Object toElement); SortedSet headSet(Object toElement); SortedSet tailSet(Object fromElement); // Endpoints Object first(); Object last(); // Comparator access Comparator comparator(); }
The operations thatSortedSet
inherits fromSet
behave identically on sorted sets and normal sets with two exceptions:Although the interface doesn't guarantee it, the
- The
Iterator
returned by theiterator
operation traverses the sorted set in order.- The array returned by
toArray
contains the sorted set's elements in order.toString
method of the JDK'sSortedSet
implementations returns a string containing all the elements of the sorted set, in order.
By convention, allCollection
implementations provide a standard constructor that takes aCollection
, andSortedSet
implementations are no exception. This constructor creates aSortedSet
object that orders its elements according to their natural order. Additionally, by convention,SortedSet
implementations provide two other standard constructors:The first of these standard constructors is the normal way to create an empty
- One that takes a
Comparator
and returns a new (empty)SortedSet
sorted according to the specifiedComparator
.- One that takes a
SortedSet
and returns a newSortedSet
containing the same elements as the givenSortedSet
, and sorted according to the sameComparator
(or using the elements' natural ordering, if the specifiedSortedSet
did too). Note that the compile-time type of the argument determines whether this constructor is invoked in preference to the ordinarySet
constructor, and not the runtime type!SortedSet
with an explicitComparator
. The second is similar in spirit to the standardCollection
constructor: it creates a copy of aSortedSet
with the same ordering, but with a programmer-specified implementation type.
The Range-view operations are somewhat analogous to those provided by theList
interface, but there is one big difference. Range-views of a sorted set remain valid even if the backing sorted set is modified directly. This is feasible because the endpoints of a range view of a sorted set are absolute points in the element-space, rather than specific elements in the backing collection (as is the case for lists). A range-view of a sorted set is really just a window onto whatever portion of the set lies in the designated part of the element-space. Changes to the range-view write back to the backing sorted set and vice-versa. Thus, it's OK to use range-views on sorted sets for long periods of time (unlike range-views on lists).Sorted sets provide three range-view operations. The first,
subSet
takes two endpoints (likesubList
). Rather than indices, the endpoints are objects. They must be comparable to the elements in the sorted set (using the set'sComparator
or the natural ordering of its elements, whichever the set uses to order itself). LikesubList
the range is half-open, including its low endpoint but excluding the high one.Thus, the following one-liner tells you how many words between "doorbell" and "pickle", including "doorbell" but excluding "pickle", are contained in a
SortedSet
of strings called dictionary:Similarly, the following one-liner removes all of the elements beginning with the letter "int count = dictionary.subSet("doorbell", "pickle").size();f
" (a rather heavy-handed approach to censorship?):A similar trick can be used to print a table telling you how many words begin with each letter:dictionary.subSet("f", "g").clear();Suppose that you want to view a closed interval (which contains both its endpoints) instead of an open interval. If the element type allows for the calculation of the successor a given value (in the element-space), merely request thefor (char ch='a'; ch<='z'; ch++) { String from = new String(new char[] {ch}); String to = new String(new char[] {(char)(ch+1)}); System.out.println(from + ": " + dictionary.subSet(from, to).size()); }subSet
fromlowEndpoint
tosuccessor(highEndpoint)
. Although it isn't entirely obvious, the successor of a strings
inString
's natural ordering iss+"\0"
(that is,s
with a null character appended).Thus, the following one-liner tells you how many words between "doorbell" and "pickle," including "doorbell" and "pickle," are contained in a the dictionary:
A similarly technique can be used to view an open interval (which contains neither endpoint). The open interval view fromint count = dictionary.subSet("doorbell", "pickle\0").size();lowEndpoint
tohighEndpoint
is the half-open interval fromsuccessor(lowEndpoint)
tohighEndpoint
. To calculate the number of words between "doorbell" and "pickle", excluding both:Theint count = dictionary.subSet("doorbell\0", "pickle").size();SortedSet
interface contains two more range-view operations,headSet
andtailSet
, both of which take a singleObject
argument. The former returns a view of the initial portion of the backingSortedSet
, up to but not including the specified object. The latter returns a view of the final portion of the the backingSortedSet
, beginning with the specified object, and continuing to the end of the backingSortedSet
Thus, the following code allows you to view the dictionary as two disjoint "volumes" (a-m and n-z):SortedSet volume1 = dictionary.headSet("n"); SortedSet volume2 = dictionary.tailSet("n");
TheSortedSet
interface contains operations to return the first and last elements in the sorted set, called (not surprisingly)first
andlast
. In addition to their obvious uses,last
allows a workaround for a deficiency in theSortedSet
interface. One thing you'd like to do with aSortedSet
is to go into the interior of the set and iterate forwards or backwards. It's easy enough to go forwards from the interior: Just get atailSet
and iterate over it. Unfortunately, there's no easy way to go backwards.The following idiom obtains the first element in a sorted set that is less than a specified object
o
in the element-space:This is a fine way to go one element backwards from a point in the interior of a sorted set. It could be applied repeatedly to iterate backwards, but unfortunately this is very inefficient, requiring a lookup for each element returned.Object predecessor = ss.headSet(o).last();
TheSortedSet
interface contains an accessor method calledcomparator
that returns theComparator
used to sort the set, ornull
if the set is sorted according to the natural order of its elements. This method is provided so that sorted sets can be copied into new sorted sets with the same ordering. It is used by the standardSortedSet
constructor, described above.
Start of Tutorial > Start of Trail > Start of Lesson | Search |