Java Reference
In-Depth Information
static double sum(List<Number> list) {
double sum = 0.0;
for (Number n : list)
sum += n.doubleValue();
return sum;
}
The intent is that sum can be passed any
List
object that has elements
that are compatible with
Number
. But that is not what the parameterized
type
List<Number>
means: It means an object compatible with
List
that
has elements declared to
be
Number
. If you try to invoke
sum
with a
List<Integer>
, for example, your code will not compile.
List<Integer> l = new ArrayList<Integer>();
l.add(1);
l.add(4);
l.add(9);
double sum = sum(l); // INVALID: won't compile
The problem is that even though
Integer
is a subtype of
Number
,
List<In-
teger>
is
not
a subtype of
List<Number>
. Contrast this with arrays, where
Integer[]
is a subtype of
Number[]
.
We need a way to declare a
List
of an arbitrary element type that is
compatible with
Number
, and the way to do that is to use the type argu-
ment
wildcard
'
?
':
static double sum(List<? extends Number> list) {
double sum = 0.0;
for (Number n : list)
sum += n.doubleValue();
return sum;
}