11.7 Generic Methods and Constructors
We first look at how generic methods and constructors are declared, and then at how they can be called—both with and without explicit actual type parameters.
Declaring Generic Methods
A generic method (also called polymorphic method) is implemented like an ordinary method, except that one or more formal type parameters are specified immediately preceding the return type. In the case of a generic constructor, the formal parameters are specified before the class name in the constructor header. Much of what applies to generic methods in this regard also applies to generic constructors.
Example 11.9 Declaring Generic Methods
public class Utilities {
// The key type and the array element type can be any type.
static boolean containsV1(Object key, Object[] array) { // (1) Non-generic
// version
for (Object element : array)
if (key.equals(element)) return true;
return false;
}
// The key type and the array element type are the same.
static <E> boolean containsV2(E key, E[] array) { // (2) Generic version
for (E element : array)
if (key.equals(element)) return true;
return false;
}
// The key type is a subtype of the array element type.
static <K extends E, E> boolean containsV3(K key, E[] array) { // (3)
for (E element : array)
if (key.equals(element)) return true;
return false;
}
}
In Example 11.9, the method containsV1() at (1) is a non-generic method to determine the membership of an arbitrary key in an arbitrary array of objects.
static boolean containsV1(Object key, Object[] array) { // (1) Non-generic version
// …
}
The method declaration at (1) is too general, in the sense that it does not express any relationship between the key and the array. This kind of type dependency between parameters can be achieved by using generic methods. In Example 11.9, the method containsV2() at (2) is a generic method to determine the membership of a key of type E in an array of type E. The type Object at (1) has been replaced by the type parameter E at (2), with the formal type parameter E being specified before the return type, in the same way as for a generic type.
static <E> boolean containsV2(E key, E[] array) { // (2) Generic version
// …
}
As with the generic types, a formal type parameter can have a bound, which is a type (i.e., not a type parameter). A formal type parameter can be used in the return type, in the formal parameter list, and in the method body. It can also be used to specify bounds in the formal type parameter list.
A generic method need not be declared in a generic type. If declared in a generic type, a generic instance method can also use the type parameters of the generic type as any other non-generic instance methods of the generic type. In contrast, a generic static method can only use the type parameters declared in its method header.
Leave a Reply