|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
ASortedSetis a
Setthat maintains its elements in ascending order, sorted according to the elements' natural order, or according to a
Comparatorprovided atSortedSetcreation time. (Natural order andComparators are discussed in the previous section, on Object Ordering.) In addition to the normalSetoperations, theSetinterface 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
Comparatorused to sort the set (if any).SortedSetinterface 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 thatSortedSetinherits fromSetbehave identically on sorted sets and normal sets with two exceptions:Although the interface doesn't guarantee it, the
- The
Iteratorreturned by theiteratoroperation traverses the sorted set in order.- The array returned by
toArraycontains the sorted set's elements in order.toStringmethod of the JDK'sSortedSetimplementations returns a string containing all the elements of the sorted set, in order.
By convention, allCollectionimplementations provide a standard constructor that takes aCollection, andSortedSetimplementations are no exception. This constructor creates aSortedSetobject that orders its elements according to their natural order. Additionally, by convention,SortedSetimplementations provide two other standard constructors:The first of these standard constructors is the normal way to create an empty
- One that takes a
Comparatorand returns a new (empty)SortedSetsorted according to the specifiedComparator.- One that takes a
SortedSetand returns a newSortedSetcontaining the same elements as the givenSortedSet, and sorted according to the sameComparator(or using the elements' natural ordering, if the specifiedSortedSetdid too). Note that the compile-time type of the argument determines whether this constructor is invoked in preference to the ordinarySetconstructor, and not the runtime type!SortedSetwith an explicitComparator. The second is similar in spirit to the standardCollectionconstructor: it creates a copy of aSortedSetwith the same ordering, but with a programmer-specified implementation type.
The Range-view operations are somewhat analogous to those provided by theListinterface, 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,
subSettakes two endpoints (likesubList). Rather than indices, the endpoints are objects. They must be comparable to the elements in the sorted set (using the set'sComparatoror the natural ordering of its elements, whichever the set uses to order itself). LikesubListthe 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
SortedSetof 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()); }subSetfromlowEndpointtosuccessor(highEndpoint). Although it isn't entirely obvious, the successor of a stringsinString's natural ordering iss+"\0"(that is,swith 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();lowEndpointtohighEndpointis 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();SortedSetinterface contains two more range-view operations,headSetandtailSet, both of which take a singleObjectargument. 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 backingSortedSetThus, 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");
TheSortedSetinterface contains operations to return the first and last elements in the sorted set, called (not surprisingly)firstandlast. In addition to their obvious uses,lastallows a workaround for a deficiency in theSortedSetinterface. One thing you'd like to do with aSortedSetis 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 atailSetand 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
oin 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();
TheSortedSetinterface contains an accessor method calledcomparatorthat returns theComparatorused to sort the set, ornullif 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 standardSortedSetconstructor, described above.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.