Java Reference
In-Depth Information
These properties of wildcards make them not only useful but essential
for effective use of generic types. Whenever a method takes a paramet-
er that is a parameterized type or returns a parameterized type, that
parameterized type should almost always be expressed with a wildcard
of some form. Typically, parameters use lower-bounded wildcards, while
return values use upper bounded wildcardsthough if there is a constraint
between a parameter type and the return type, it may not be possible
to use a wildcard. Even a type bound that is a parameterized type will
often be expressed with a wildcard. Recall the example of the SortedCol-
lection<E> interface, in which we constrained the type parameter E such
that E extends Comparable<E> . This seemed reasonable: to sort the collec-
tion we need the elements to be comparable to each other. In fact, this
constraint is overly tightfor two elements of a class T to be comparable
to each other, it is not necessary that T extend Comparable<T> but only
that T extend Comparable<S> where S is T or any supertype of T . For ex-
ample, if class Value implements Comparable<Object> then it can still cor-
rectly compare two Value objectsit just happens to be able to do more
than that. Consequently, SortedCollection should be declared as follows:
interface SortedCollection<E extends Comparable<? super E>>
{
// ... sorted collection methods ...
}
 
Search WWH ::




Custom Search