Java Reference
In-Depth Information
TIP:
(continued)
will be inherited, so you need not worry too much about it. If you are defining a col-
lection class from scratch and want your class to implement one of the collection inter-
faces, then you do need to throw suitable exceptions as specified for the interface.
With one exception (no pun intended), all the exception classes mentioned in this
chapter are in the package
java.lang
and so do not require any import statement. The
one exception is the
NoSuchElementException
, which is used with iterators in Section
16.3. The
NoSuchElementException
is in the
java.util
package, which requires an
import statement if your code mentions the
NoSuchElementException
class.
■
Self-Test Exercises
1. Give the definition of a
boolean
valued static generic method named
inSome
. The
method
inSome
has two parameters of type
Collection<T>
and one parameter of
type
T
. The method returns
true
if the parameter of type
T
is in either (or both)
collections; it returns
false
otherwise.
2. Give the definition of a static generic method named
getFirst
that has one
parameter of type
List<T>
and a return type of
T
. The method returns the first
element in the list or
null
if the list is empty.
3. Give the definition of a static
boolean
valued method named
noNull
. The
method
noNull
has one parameter of type
Set<?>
and removes
null
from the set
if
null
is in the set; otherwise it leaves the set unchanged. The method returns
true
if the set is changed and
false
if it is not changed.
Concrete Collection Classes
The abstract classes
AbstractSet<T>
and
AbstractList<T>
are there for convenience
when implementing the
Set<T>
and
List<T>
interfaces, respectively. They have almost
no methods beyond those in the interfaces they implement. Although these two
abstract classes have only a few abstract methods, the other (nonabstract) methods
have fairly useless implementations that must be overridden. When defining a derived
class of either
AbstractSet<T>
or
AbstractList<T>
, you need to define not just the
abstract methods but also all the methods you intend to use. It usually makes more
sense to simply use (or define derived classes of ) the
HashSet<T>
,
ArrayList<T>
, or
Vector<T>
classes, which are derived classes of
AbstractSet<T>
and
AbstractList<T>
and are full implementations of the
Set<T>
and
List<T>
interfaces.
The abstract class
AbstractCollection<T>
is a skeleton class for the
Collection<T>
interface. Although it is perfectly legal, you seldom, if ever, need to define a derived
class of the
AbstractCollection<T>
class. Instead, you normally define a derived class
of one of the descendent classes of the
AbstractCollection<T>
class.
Abstract-
Set<T>
Abstract-
List<T>
Abstract-
Collection<T>