Type Parameters
Fundamentals
What is a type parameter?
A place holder for a type argument. | |
Generic types have one or more type parameters. Example of a parameterized type: interface Comparable<E> {The identifier E is a type parameter. Each type parameter is replaced by a type argument when an instantiation of the generic type, such as Comparable<Object> or Comparable<? extends Number> , is used. |
|
LINK TO THIS | TypeParameters.FAQ001 |
REFERENCES | How is a generic type defined? What is a bounded type parameter? Where is a type parameter visible (or invisible)? |
What is a bounded type parameter?
A type parameter with one or more bounds. The bounds restrict the set of types that can be used as type arguments and give access to the methods defined by the bounds. | |
When you declare a type parameter T and use it in the implementation of a generic type or method, the type parameter T still denotes an unknown type. The compiler knows that T is a place holder for a type, but it does not know anything about the type. This is okay in some implementations, but insufficient in others. Example (of a generic type without bounds): public class Hashtable<Key,Data> {The implementation of class Hashtable invokes the methods hashCode and equals on the unknown Key type. Since hashCode and equals are methods defined in class Object and available for all reference types, not much need to be known about the unknown Key type. This changes substantially, when we look into the implementation of sorted sequence. Example (of a generic type, so far without bounds): public interface Comparable<T> {The implementation of class TreeMap invokes the method compareTo on the unknown Key type. Since compareTo is not defined for arbitrary types the compiler refuses to invoke the compareTo method on the unknown type Key because it does not know whether the key type has a compareTo method. In order to allow the invocation of the compareTo method we must tell the compiler that the unknown Key type has a compareTo method. We can do so by saying that the Key type implements the Comparable<Key> interface. We can say so by declaring the type parameter Key as a bounded parameter. Example (of the same generic type, this time with bounds): public interface Comparable<T> {In the example above, the type parameter Key has the bound Comparable<Key> . Specification of a bound has two effects:
|
|
LINK TO THIS | TypeParameters.FAQ002 |
REFERENCES | When would I use a wildcard parameterized with a lower bound? What is a type parameter bound? Which types are permitted as type parameter bounds? Can I use different instantiations of a same generic type as bounds of a type parameteer? |