Java Reference
In-Depth Information
Noncompliant Code Example (Generic Type)
This noncompliant code example declares the same variable arity method using a generic
type parameter. It accepts a variable number of parameters that are all of the same object
type; however, it may be any object type. Again, legitimate uses of such declarations are
rare.
Click here to view code image
<T> double sum(T... args) {
// ...
}
Compliant Solution (Generic Type)
This compliant solution defines the same generic method using the Number type.
Click here to view code image
<T extends Number> double sum(T... args) {
// ...
}
Beasspecificaspossiblewhendeclaringparametertypes;avoid Object andimprecise
generic types in variable arity methods. Retrofitting old methods containing final array
parameters withgenerically typedvariable arity parameters isnotalways agoodidea. For
example, given a method that does not accept an argument of a particular type, it could
be possible to override the compile-time checking—through the use of generic variable
arityparameters—sothatthemethodwouldcompilecleanlyratherthancorrectly,causing
a runtime error [Bloch 2008].
Also, note that autoboxing prevents strong compile-time type checking of primitive
types and their corresponding wrapper classes. For example, this compliant solution pro-
duces the following warning, but works as expected:
Click here to view code image
Java.java:10: warning: [unchecked] Possible heap pollution from
parameterized vararg type T
<T extends Number> double sum(T... args) {
This particular compiler warning can be safely ignored.
Search WWH ::




Custom Search