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 Exercise 2.2 and rewrite it as a generic
class.
Exercise 11.2: Rewrite the Attr class from Chapter 3 as a generic class.
Exercise 11.3: Was Exercise 11.2 a good idea? How does Attr being generic affect the Attributed
interface defined in Chapter 4? What does it mean for Attributed objects?
11.1.1. Bounded Type Parameters
In the generic class declaration of Cell
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 implement 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 compared
with other objects of that same type, so typically a class Value that is comparable will be declared as
class Value implements Comparable
// ...
}
So a sorted collection would restrict its type parameter to be a type that implements Comparable:[2]
[2] You'll see a little later (page 258) that it's better to actually declare this slightly differently,
but for now we keep it simple.
interface SortedCollection<E extends Comparable
// ... sorted collection methods ...
}
Here E is restricted to be a type that "extends" Comparable
argument is supplied, it is guaranteed to support the methods of the Comparable interface. We say that
Comparable is the upper bound on the type of E, and that E is a bounded type parameter. The keyword
extends is used here in a very general way to mean either "extends" or "implements," depending on
whether the type that follows is a class type or an interface type. Any given class can extend only one other
class, but multiple interfaces can be implemented by classes or interfaces. A type bound can express such
multiple dependencies by declaring that the type parameter extends one class or interface, followed by an
ampersand (&) separated list of additional interfaces that must be implemented. For example, a sorted
collection of character sequences could be declared as follows:
interface SortedCharSeqCollection<E extends Comparable
& CharSequence> {
// ... sorted char sequence collection methods ...
}
Such a collection could hold String objects, for example.