Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
is made to add duplicate elements to a set. It does not define any additional methods of its
own.Setis a generic interface that has this declaration:

interface Set<E>

Here,Especifies the type of objects that the set will hold.

The SortedSet Interface


TheSortedSetinterface extendsSetand declares the behavior of a set sorted in ascending
order.SortedSetis a generic interface that has this declaration:

interface SortedSet<E>

Here,Especifies the type of objects that the set will hold.
In addition to those methods defined bySet, theSortedSetinterface declares the methods
summarized in Table 17-3. Several methods throw aNoSuchElementExceptionwhen no
items are contained in the invoking set. AClassCastExceptionis thrown when an object
is incompatible with the elements in a set. ANullPointerExceptionis thrown if an attempt is
made to use anullobject andnullis not allowed in the set. AnIllegalArgumentException
is thrown if an invalid argument is used.
SortedSetdefines several methods that make set processing more convenient. To obtain
the first object in the set, callfirst( ). To get the last element, uselast( ). You can obtain a subset
of a sorted set by callingsubSet( ), specifying the first and last object in the set. If you need
the subset that starts with the first element in the set, useheadSet( ). If you want the subset
that ends the set, usetailSet( ).

The NavigableSet Interface


TheNavigableSetinterface was added by Java SE 6. It extendsSortedSetand declares the
behavior of a collection that supports the retrieval of elements based on the closest match to
a given value or values.NavigableSetis a generic interface that has this declaration:

interface NavigableSet<E>

Here,Especifies the type of objects that the set will hold. In addition to the methods
that it inherits fromSortedSet,NavigableSetadds those summarized in Table 17-4. A

444 Part II: The Java Library


Method Description
Comparator<? super E> comparator( ) Returns the invoking sor ted set’s comparator. If the natural ordering
is used for this set,nullis returned.
E first( ) Returns the first element in the invoking sor ted set.
Sor tedSet<E> headSet(Eend) Returns aSortedSetcontaining those elements less thanendthat
are contained in the invoking sor ted set. Elements in the returned
sor ted set are also referenced by the invoking sor ted set.
E last( ) Returns the last element in the invoking sor ted set.
Sor tedSet<E> subSet(Estar t, Eend) Returns aSortedSetthat includes those elements betweenstar t
andend–1. Elements in the returned collection are also referenced
by the invoking object.
Sor tedSet<E> tailSet(Estar t) Returns aSortedSetthat contains those elements greater than or
equal tostar tthat are contained in the sor ted set. Elements in the
returned set are also referenced by the invoking object.

TABLE 17-3 The Methods Defined bySortedSet
Free download pdf