Friday, July 04, 2008

Generics Wildcards

Wildcards are useful with generics because they are not covariant unlike arrays. For example an array of Integer is also an array of Number, but a generic List of Integer is not a generic List of Number.

Upper-bound wildcards place an upper bound on the type: ? extends T
Lower-bound wildcards place a lower bound on the type: ? super T

The get-put principle acts as a reminder of which wildcard to use:
"Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you do both."

An example using both upper and lower-bound wildcards:
public static<T> void copy(
Box<? extends T> from,
Box<? super T> to) {
to.put(from.get());
}
See: Java theory and practice: Going wild with generics

No comments: