Java Reference
In-Depth Information
Suppose you have a SingleLinkQueue<Object> that you know you have
filled only with String instanceswhy shouldn't you be able to pass toArray
a String[] ? Yet String is not a supertype of Object . So in fact there is no
compile-time type checking between T and E to see if they are compat-
ible. We instead rely on the runtime type check that always occurs when
a reference is stored into an array.
Generic methods and constructors are typically used when you need to
introduce a type variable to constrain the parameterized types of differ-
ent parameters, or to constrain a parameter and the return type, as with
toArray . For example, consider a merge operation for SingleLinkQueue that
moves the elements from a source queue into a destination queue. To
perform a merge, the elements of the source queue must be the same
as, or a subtype of, the elements of the destination queue. You can ex-
press this constraint with a generic method by using a wildcard:
public static <E> void merge(SingleLinkQueue<E> d,
SingleLinkQueue<? extends E> s)
{
// ... merge s elements into d ...
}
We could have introduced a second type variable, say S , to use instead
of the wildcard to achieve the same affect. So which is preferable? The
general rule is to use wildcards when you can because code with wild-
cards is generally more readable than code with multiple type paramet-
ers. When deciding if you need a type variable, ask yourself if that type
variable is used to relate two or more parameters, or to relate a para-
meter type with the return type. If the answer is no, then a wildcard
should suffice. In the above example, S would appear in only one place
and so can trivially be replaced by a wildcard.
A generic method need not be declared in a generic type, and if it is then
the type variables are distinct. As with inner generic types, if a gener-
ic method declares a type variable of the same name as that of a type
variable in the method's class or interface, the outer name is hidden.
 
Search WWH ::




Custom Search