Java Reference
In-Depth Information
you can use
addAll
to add a
LinkedList<SavingsAccount>
to a
LinkedList<BankAccount>
.
To see a wildcard with a
super
bound, have another look at the
min
method of
the preceding section. Recall that
Comparable
is a generic interface; the type
parameter of the
Comparable
interface specifies the parameter type of the
compareTo
method.
public interface Comparable<T>
{
int compareTo(
T
other)
}
Therefore, we might want to specify a type bound:
public static <E extends Comparable
<E>
> E min(E[]
a)
However, this bound is too restrictive. Suppose the
BankAccount
class
implements
Comparable<BankAccount>
. Then the subclass
SavingsAccount
also implements
Comparable<BankAccount>
and not
Comparable<SavingsAccount>
. If you want to use the
min
method with a
SavingsAccount
array, then the type parameter of the
Comparable
interface
should be any supertype of the array element type:
public static <E extends Comparable<
? super E
>> E
min(E[] a)
Here is an example of an unbounded wildcard. The
Collections
class defines a
method
public static void reverse(List<?> list)
You can think of that declaration as a shorthand for
public static <T> void reverse(List<T> list)
779
780
17.5 Raw Types
The virtual machine that executes Java programs does not work with generic classes
or methods. Instead, it uses raw types, in which the type variables are replaced with