THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
public voidclear()

Removes all elements from this collection. (Optional)

This Collection interface is purposely very general. Each specific collection type can define restrictions
on its parameters or other related behavior. A collection may or may not accept null elements, may be
restricted to certain types of elements, may retain elements in a sorted order, and so on. Each collection that
makes a restriction should state those restrictions in its documentation so that users can understand the
contract for that collection.


21.5. Set and SortedSet


The Set interface extends Collection, providing a more specific contract for its methods, but
adds no new methods of its own. A collection that is a Set contains no duplicate elements. If you add the
same element twice to a set (in other words, if you add two objects that are equal), the first invocation will
return TRue, while the second will return false. If after this, remove is similarly invoked twice, the first
remove of the element will return TRue since the set was changed by removing the element, while the
second will return false since the element was no longer present. A set may also contain at most one null
element.


The SortedSet interface extends Set to specify an additional contractiterators on such a set will
always return the elements in a specified order. By default this will be the element's natural order. In the
implementations of SortedSet provided in java.util you can also specify a Comparator object that
will be used to order the elements instead of the natural order.


SortedSet adds some methods that make sense in an ordered set:


public Comparator<? super E>comparator()

Returns the Comparator being used by this sorted set, or null if the
elements' natural order is being used. Note the use of the lower bounded
wildcard in the return type; any implementation of this interface should
accept a comparator that is typed the same way.

public Efirst()

Returns the first (lowest) object in this set.

public Elast()

Returns the last (highest) object in this set.

public SortedSet<E>subSet(E min, E max)

Returns a view of the set that contains all the elements of this set whose
values are greater than or equal to min and less than max. The view is
backed by the collection; that is, changes to the collection that fall within the
range will be visible through the returned subset and vice versa. If min is
greater than max, or if this set is itself a view of another set and min or max
fall outside the range of that view, an IllegalArgumentException is
thrown. You will also get an IllegalArgumentException if you
attempt to modify the returned set to contain an element that is outside the
specified range.
Free download pdf