Java Reference
In-Depth Information
Display 16.2
Method Headings in the
Collection<T>
Interface
(part 3 of 3)
OPTIONAL METHODS
The following methods are optional, which means they still must be implemented, but the imple-
mentation can simply throw an
UnsupportedOperationException
if, for some reason, you do
not want to give them a “real” implementation. An
UnsupportedOperationException
is a
RunTimeException
and so is not required to be caught or declared in a
throws
clause.
public
boolean
add(T element) (Optional)
Ensures that the calling object contains the specified
element
. Returns
true
if the calling object
changed as a result of the call. Returns
false
if the calling object does not permit duplicates and already
contains
element
; also returns
false
if the calling object does not change for any other reason.
public
boolean
addAll(Collection<? extends T> collectionToAdd) (Optional)
Ensures that the calling object contains all the elements in
collectionToAdd
. Returns
true
if
the calling object changed as a result of the call; returns
false
otherwise.
public
boolean
remove(Object element) (Optional)
Removes a single instance of the element from the calling object, if it is present. Returns
true
if
the calling object contained the element; returns
false
otherwise.
public
boolean
removeAll(Collection<?> collectionToRemove) (Optional)
Removes all the calling object's elements that are also contained in
collectionToRemove
.
Returns
true
if the calling object was changed; otherwise returns
false
.
public
void
clear( ) (Optional)
Removes all the elements from the calling object.
public
boolean
retainAll(Collection<?> saveElements) (Optional)
Retains only the elements in the calling object that are also contained in the collection
saveElements
.
In other words, removes from the calling object all of its elements that are not contained in the collec-
tion
saveElements
. Returns
true
if the calling object was changed; otherwise returns
false
.
Packages
All the collection classes and interfaces discussed in this chapter are in the
java
.
util
package.
The relationships between some of the classes and interfaces that implement or
extend the
Collection<T>
interface are given in Display 16.1. There are two main
interfaces that extend the
Collection<T>
interface: the
Set
<
T>
interface and the
List
<
T
> interface. Classes that implement the
Set<T>
interface do not allow an element
Set<T> List
interfaces