Java Reference
In-Depth Information
In order to make the method into a generic method, replace String with a type
variable, say E , to denote the element type of the array. Add a type variable list,
enclosed in angle brackets, between the modifiers ( public static ) and the return
type ( void ):
public static <E> void print( E [] a)
{
for ( E e : a)
System.out.print(e + Ð Ñ);
System.out.println();
}
When you call the generic method, you need not specify which type to use for the
type variable. (In this regard, generic methods differ from generic classes.) Simply
call the method with appropriate parameters, and the compiler will match up the type
variables with the parameter types. For example, consider this method call:
Rectangle[] rectangles = . . . ;
ArrayUtil.print(rectangles);
The type of the rectangles parameter is Rectangle[] , and the type of the
parameter variable is E[] . The compiler deduces that E is Rectangle .
When calling a generic method, you need not instantiate the type variables.
This particular generic method is a static method in an ordinary class. You can also
define generic methods that are not static. You can even have generic methods in
generic classes.
776
777
S YNTAX 17.3 Defining a Generic Method
modifiers <Type Variable 1 , TypeVariable 2 , . . .>
returnType methodName(parameters)
{
body
}
Example:
public static <E> void print( E [] a)
{
Search WWH ::




Custom Search