Java Reference
In-Depth Information
54
// calculate sum
55
for (Number element : list)
56
total += element.doubleValue();
57
58
return total;
59
}
60
} // end class WildcardTest
integerList contains: [1, 2, 3, 4, 5]
Total of the elements in integerList: 15
doubleList contains: [1.1, 3.3, 5.5]
Total of the elements in doubleList: 9.9
numberList contains: [1, 2.4, 3, 4.1]
Total of the elements in numberList: 10.5
Fig. 20.14 | Wildcard test program. (Part 2 of 2.)
Lines 11-20 create and initialize an ArrayList<Integer> , output its elements and
total them by calling method sum (line 20). Lines 24-33 perform the same operations for
an ArrayList<Double> . Lines 37-46 perform the same operations for an Array-
List<Number> that contains Integer s and Double s.
In method sum (lines 50-59), although the ArrayList argument's element types are
not directly known by the method, they're known to be at least of type Number , because
the wildcard was specified with the upper bound Number . For this reason line 56 is allowed,
because all Number objects have a doubleValue method.
Although wildcards provide flexibility when passing parameterized types to a method,
they also have some disadvantages. Because the wildcard ( ? ) in the method's header (line
50) does not specify a type-parameter name, you cannot use it as a type name throughout
the method's body (i.e., you cannot replace Number with ? in line 55). You could, however,
declare method sum as follows:
public static <T extends Number> double sum(ArrayList<T> list)
which allows the method to receive an ArrayList that contains elements of any Number
subclass. You could then use the type parameter T throughout the method body.
If the wildcard is specified without an upper bound, then only the methods of type
Object can be invoked on values of the wildcard type. Also, methods that use wildcards in
their parameter's type arguments cannot be used to add elements to a collection referenced
by the parameter.
Common Programming Error 20.3
Using a wildcard in a method's type-parameter section or using a wildcard as an explicit
type of a variable in the method body is a syntax error.
20.9 Wrap-Up
This chapter introduced generics. You learned how to declare generic methods and classes
with type parameters specified in type-parameter sections. You also learned how to specify
 
 
Search WWH ::




Custom Search