Wildcards
We mentioned earlier that the kinds of generic type instantiations
discussed so far in this chapter have all been concrete type
instantiations. We described this as meaning that all of the parameter
arguments are real Java types. For example, List<String> and List<Date> are instantiations of the
generic List class with the concrete
types String and Date. Now we’re going to look at another kind of
generic type instantiation: wildcard
instantiation.
As we’ll see in this section, wildcards are Java’s way of
introducing polymorphism into the type parameter portion of the generic
equation. A wildcard instantiation uses a question mark (?) in place of an actual type parameter at
instantiation time and denotes that the type can be assigned any of a
range of possible instantiations of the generic type. The ? wildcard by itself is
called the unbounded wildcard and denotes that any
type instantiation is acceptable (assignable to the type).
List<?>anyInstantiationOfList=newArrayList<Date>();anyInstantiationOfList=newArrayList<String>();// another instantiation
In this snippet, we declared a variable anyInstantiationOfList whose type is the
unbounded wildcard instantiation of the generic List type. (What a mouthful.) This means that
the type we instantiated can be assigned any particular concrete
instantiation of the List type, whether
Dates, Strings, or Foos. Here, we assigned it a List<Date> first and, subsequently, a
List<String>.
A Supertype of All Instantiations
The unbounded ...