Java Reference
In-Depth Information
ArrayList<SavingsAccount> savingsAccounts
= new ArrayList<SavingsAccount>();
ArrayList<BankAccount> bankAccounts =
savingsAccounts;
// Not legal, but suppose it was
BankAccount harrysChecking = new CheckingAccount();
bankAccounts.add(harrysChecking); // OKÏcan add
BankAccount object
But
bankAccounts
and
savingsAccounts
refer to the same array list! If the
assignment was legal, we would be able to add a
CheckingAccount
into an
ArrayList<SavingsAccount>
.
In many situations, this limitation can be overcome by using wildcardsȌsee
Advanced Topic 17.1
.
A
DVANCED
T
OPIC
17.1: Wildcard Types
It is often necessary to formulate subtle constraints of type variables. Wildcard
types were invented for this purpose. There are three kinds of wildcard types:
Name
Syntax
Meaning
Wildcard with lower bound
? extends B
Any subtype of B
Wildcard with upper bound
? super B
Any supertype of
B
Unbounded wildcard
?
Any type
A wildcard type is a type that can remain unknown. For example, we can define
the following method in the
LinkedList<E>
class:
public void addAll(LinkedList<? extends E> other)
{
ListIterator<E> iter = other.listIterator();
while (iter.hasNext()) add(iter.next());
}
The method adds all elements of
other
to the end of the linked list.
The
addAll
method doesn't require a specific type for the element type of
other
. Instead, it allows you to use any type that is a subtype of
E
. For example,