When your entire class does not need to be generic, but one or more methods within the class do need to be generic, you can create a generic method. A generic method is a method that has generic parameter types and/or generic return types. For example:
// notice that the class is not generic
class Demo {
// notice that this method is generic
public static <E> void printArray(E[] inputArray){ ... }
}
In the example above, the printArray() method is a generic method that exists within a non-generic class. When using generic methods, you'll notice the diamond brackets with the type parameter before the return type. You'll also notice that the inputArray is of type E.
Rules for Defining a Generic Method
The following are the four rules for defining generic methods in Java.
Every generic method declaration includes a type parameter section enclosed by diamond brackets placed before the method's return type (as seen in the example below, where
Generic Method Signature
When defining a generic method, a bit of new syntax is used in the method signature. The generic parameter, for example, <E> below, must be specified before the method name.
Generic Method Example
The following example illustrates how you can
public class GenericMethodTest {
// declare generic printArray() method
public static < E > void printArray( E[] inputArray ) {
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
/* Create arrays of Integer,
Double and Character */
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
/* pass an Integer array */
printArray(intArray);
System.out.println("Array doubleArray contains:");
/* pass a Double array */
printArray(doubleArray);
System.out.println("Array characterArray contains:");
/* pass a Character array */
printArray(charArray);
}
}
Summary: What is a Java Generic Method
- A generic method is a method that has generic parameter types and/or generic return types
- Generic methods are used when only itself and not the entire class need the generic type
- The generic parameter must be defined before the return type as well as in the parameter list