Java Reference
In-Depth Information
11.2. Working with Generic Types
To use a generic type you define a suitable parameterized type that
provides the desired type arguments for each type parameter. For ex-
ample, you previously saw:
SingleLinkQueue<String> queue =
new SingleLinkQueue<String>();
The variable
queue
is of type
SingleLinkQueue<String>
, and the constructor
invocation also declares the parameterized type
SingleLinkQueue<String>
.
A parameterized type must supply a type argument for each type para-
meter declared by the generic type.
Working with generic types requires a little more planning than working
with non-generic types: When you need to declare a field or local vari-
able, or a method parameter or return type, you need to specify the ap-
propriate parameterized type that you intend to work with. For example,
should a field be of type
SingleLinkQueue<String>
or
SingleLinkQueue<Num-
ber>
, or should it be able to refer to any queue, perhaps
SingleLinkQueue<Object>
? This seems an easy enough question to answer-
indeed it seems we did just answer it: You should specify a type argu-
ment that is assignable by all the types you expect. The problem is that
the way you specify such a type is not the way we just illustrated be-
cause generic types don't form subtypes in the way you might think.
11.2.1. Subtyping and Wildcards
Suppose you want to write a method to sum all of the elements in a
require that the list that gets passed contains only
Number
objects. The
following code would seem to do the trick: