Java Reference
In-Depth Information
you, an array of the right size and typewhich we show you a little lateror
you could have the caller provide the
type token
for
E
(the
Class
object
for the actual type argument) and use reflection to create an array of
the right sizesee "
Genericity and Dynamic Arrays
" on page
430
.
Exercise 11.1
: Revisit the
LinkedList
class that you started back in Ex-
ercise 2.2 and rewrite it as a generic class.
Exercise 11.3
: Was Exercise 11.2 a good idea? How does
Attr
being
it mean for
Attributed
objects?
11.1.1. Bounded Type Parameters
In the generic class declaration of
Cell<E>
, the type variable
E
can be
replaced by absolutely any reference type. Sometimes it doesn't make
sense to allow an arbitrary type argument to be used with a generic
type. For example, a sorted collection can hold any type of object as
long as that object can be sorted. As you have seen a number of times
now, the way to define something that can be sorted is to have it im-
plement the
Comparable
interface.
Comparable
itself is a generic interface,
with a single type variable that identifies what type the current type can
be compared with. Usually, objects of a given type should only be com-
pared with other objects of that same type, so typically a class
Value
that is comparable will be declared as
class Value implements Comparable<Value> {
// ...
}
So a sorted collection would restrict its type parameter to be a type that