Java Reference
In-Depth Information
When you define a generic class, you can use the type parameter in the definitions
of the methods for that generic class. You also can define a generic method that has its
own type parameter that is not the type parameter of any class. This generic method
can be a member of an ordinary (nongeneric) class or a member of some generic class
with some other type parameter. For example,
public class Utility
{
...
public static <T> T getMidpoint(T[] a)
{
return a[a.length/2];
}
public static <T> T getFirst(T[] a)
{
return a[0];
}
...
}
In this case, the class ( Utility ) has no type parameters, but the methods getMidpoint
and getFirst each have a type parameter. Note that the type parameter in angular
brackets, <T> , is placed after all the modifiers, in this case public static , and before
the returned type.
When you invoke one of these generic methods, you preface the method name
with the type to be plugged in, given in angular brackets, as in the following examples:
String midString = Utility.<String>getMidpoint(b);
double firstNumber = Utility.<Double>getFirst(c);
Note that the dot is before the type in angular brackets; the type is part of the method
name, not part of the class name. Also note that the methods getMidpoint and getFirst
use different types plugged in for their type parameter. The type parameter is local to the
method, not to the class. (The argument b is an array with base type String . The argu-
ment c is an array with base type Double .)
You can also define such generic methods inside of generic classes, as in the follow-
ing example:
public class Sample<T>
{
private T data;
public Sample(T forData)
{
data = forData;
}
Search WWH ::




Custom Search