Java Reference
In-Depth Information
Our
LinkedList
class implements genericity by using inheritance. It stores objects
of any class that inherits from
Object
. In contrast, the
ArrayList
class uses type
variables to achieve genericityȌyou need to specify the type of the objects that you
want to store.
Note that only our
LinkedList
class of
Chapter 15
uses inheritance. The standard
Java library has a
LinkedList
class that uses type variables. In the next section, we
will add type variables to our
LinkedList
class as well.
A generic class has one or more type variables.
The
ArrayList
class is a generic class: it has been declared with a type variable
E
.
The type variable denotes the element type:
public class ArrayList
<E>
{
public ArrayList() { . . . }
public void add(
E
element) {. . .}
. . .
}
Here,
E
is the name of a type variable, not a Java keyword. You could use another
name, such as
ElementType
, instead of
E
. However, it is customary to use short,
uppercase names for type parameters.
Type variables can be instantiated with class or interface types.
766
767
In order to use a generic class, you need to instantiate the type variable, that is,
supply an actual type. You can supply any class or interface type, for example
ArrayList<BankAccount>
ArrayList<Measurable>
However, you cannot substitute any of the eight primitive types for a type variable. It
would be an error to declare an
ArrayList<double>
. Use the corresponding
wrapper class instead, such as
ArrayList<Double>
.