Java Reference
In-Depth Information
you want this method to be able to work properly no matter what type of number each ob-
ject holds. For example, if one object contains the
Double
value 1.25 and the other object
contains the
Float
value -1.25, then
absEqual( )
would return true. One way to implement
absEqual( )
is to pass it a
NumericFns
argument, and then compare the absolute value of
that argument against the absolute value of the invoking object, returning true only if the
values are the same. For example, you want to be able to call
absEqual( )
, as shown here:
At first, creating
absEqual( )
seems like an easy task. Unfortunately, trouble starts as
soon as you try to declare a parameter of type
NumericFns
. What type do you specify for
NumericFns
' type parameter? At first, you might think of a solution like this, in which
T
is used as the type parameter:
Here, the standard method
Math.abs( )
is used to obtain the absolute value of each number,
and then the values are compared. The trouble with this attempt is that it will work only
with other
NumericFns
objects whose type is the same as the invoking object. For ex-
ample, if the invoking object is of type
NumericFns<Integer>
, then the parameter
ob
must also be of type
NumericFns<Integer>
. It can't be used to compare an object of type
NumericFns<Double>
, for example. Therefore, this approach does not yield a general
(i.e., generic) solution.
To create a generic
absEqual( )
method, you must use another feature of Java generics:
the
wildcard argument
. The wildcard argument is specified by the
?
, and it represents an
unknown type. Using a wildcard, here is one way to write the
absEqual( )
method: