Java Reference
In-Depth Information
interface Box < T > {
void box ( T t );
T unbox ();
}
This indicates that the Box interface is a general construct, which can hold any type
of payload. It isn't really a complete interface by itself—it's more like a general
description of a whole family of interfaces, one for each type that can be used in
place of T .
Generic Types and Type Parameters
We've seen how to use a generic type, to provide enhanced program safety, by using
compile-time knowledge to prevent simple type errors. In this section, let's dig
deeper into the properties of generic types.
The syntax <T> has a special name—it's called a type parameter , and another name
for a generic type is a parameterized type . This should convey the sense that the con‐
tainer type (e.g., List ) is parameterized by another type (the payload type). When
we write a type like Map<String, Integer> , we are assigning concrete values to the
type parameters.
When we define a type that has parameters, we need to do so in a way that does not
make assumptions about the type parameters. So the List type is declared in a
generic way as List<E> , and the type parameter E is used all the way through to
stand as a placeholder for the actual type that the programmer will use for the pay‐
load when she makes use of the List data structure.
Type parameters always stand in for reference types. It is not
possible to use a primitive type as a value for a type parameter.
The type parameter can be used in the signatures and bodies of methods as though
it is a real type, for example:
interface List < E > extends Collection < E > {
boolean add ( E e );
E get ( int index );
// other methods omitted
}
Note how the type parameter E can be used as a parameter for both return types
and method arguments. We don't assume that the payload type has any specific
properties, and only make the basic assumption of consistency—that the type we
put in is the sane type that we will later get back out.
Search WWH ::




Custom Search