Now, notice how isIn( ) is called within main( ) by use of the normal call syntax, without
the need to specify type arguments. This is because the types of the arguments are automatically
discerned, and the types of T and V are adjusted accordingly. For example, in the first call:
if(isIn(2, nums))
the type of the first argument is Integer (due to autoboxing), which causes Integer to be
substituted for T. The base type of the second argument is also Integer, which makes Integer
a substitute for V, too.
In the second call, String types are used, and the types of T and V are replaced by String.
Now, notice the commented-out code, shown here:
//
if(isIn("two", nums))
//
System.out.println("two is in strs");
If you remove the comments and then try to compile the program, you will receive an error. The
reason is that the type parameter V is bounded by T in the extends clause in V's declaration.
This means that V must be either type T, or a subclass of T. In this case, the first argument is of
type String, making T into String, but the second argument is of type Integer, which is not a
subclass of String. This causes a compile-time type-mismatch error. This ability to enforce type
safety is one of the most important advantages of generic methods.
The syntax used to create isIn( ) can be generalized. Here is the syntax for a generic method:
<type-param-list> ret-type meth-name(param-list) { // ...
In all cases, type-param-list is a comma-separated list of type parameters. Notice that for
a generic method, the type parameter list precedes the return type.
Generic Constructors
It is also possible for constructors to be generic, even if their class is not. For example, consider
the following short program:
// Use a generic constructor.
class GenCons {
private double val;
<T extends Number> GenCons(T arg) {
val = arg.doubleValue();
}
void showval() {
System.out.println("val: " + val);
}
}
class GenConsDemo {
public static void main(String args[]) {
GenCons test = new GenCons(100);
GenCons test2 = new GenCons(123.5F);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home