Java Reference
In-Depth Information
1
package weiss.util;
2
3
/**
4
* SortedSet interface.
5
*/
6
public interface SortedSet<AnyType> extends Set<AnyType>
7
{
8
/**
9
* Return the comparator used by this SortedSet.
10
* @return the comparator or null if the
11
* default comparator is used.
12
*/
13
Comparator<? super AnyType> comparator( );
14
15
/**
16
* Find the smallest item in the set.
17
* @return the smallest item.
18
* @throws NoSuchElementException if the set is empty.
19
*/
20
AnyType first( );
21
22
/**
23
* Find the largest item in the set.
24
* @return the largest item.
25
* @throws NoSuchElementException if the set is empty.
26
*/
27
figure 6.30
Possible
SortedSet
interface
AnyType last( );
28
}
A
SortedSet
is a
Set
that maintains (internally) its items in sorted order.
Objects that are added into the
SortedSet
must either be comparable, or a
Comparator
has to be provided when the container is instantiated. A
SortedSet
supports all of the
Set
methods, but its iterator is guaranteed to step through
items in its sorted order. The
SortedSet
also allows us to find the smallest
and largest item. The interface for our subset of
SortedSet
is shown in
Figure 6.30.
The
SortedSet
is an
ordered container.
It allows no
duplicates.
6.7.1
the
TreeSet
class
The
SortedSet
is implemented by a
TreeSet
. The underlying implementation
of the
TreeSet
is a balanced-binary search tree and is discussed in Chapter 19.
By default, ordering uses the default comparator. An alternate ordering
can be specified by providing a comparator to the constructor. As an example,
Figure 6.31 illustrates how a
SortedSet
that stores strings is constructed. The
call to
printCollection
will output elements in decreasing sorted order.
The
SortedSet
, like all
Set
s, does not allow duplicates. Two items are con-
sidered equal if the comparator's
compare
method returns 0.
The
TreeSet
is an
implementation of
SortedSet
.
Search WWH ::
Custom Search