Generic Methods
TL;DR
- A Generic Method defines its own type parameter(s), independent of the class it resides in.
- The type parameter
<T>is declared before the return type in the method signature. - Even non-generic classes can contain generic methods.
Concept
Sometimes you don’t need the entire class to be generic. If you are writing a utility method that needs to process arrays of different types, making the method generic is sufficient.
By placing <T> before the return type, you tell the compiler that T is a generic type specific to this single method invocation. The compiler will automatically infer the concrete type based on the arguments you pass into the method.
Examples
public class GenericMethodExample {
// A Generic Method.
// <T> is the type parameter declaration.
// T[] is the parameter type.
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
// A Generic Method returning a Generic Type
public static <T> T getFirstElement(T[] array) {
if (array == null || array.length == 0) {
return null;
}
return array[0];
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] strArray = {"Hello", "World"};
// The compiler infers T as Integer
printArray(intArray);
// The compiler infers T as String
printArray(strArray);
String first = getFirstElement(strArray);
}
}
Interview Questions
Q: Can generic methods be static?
A: Yes, generic methods can definitely be static. In fact, static generic methods are extremely common in utility classes (like Collections.sort()). Because static methods cannot access class-level type parameters (since static methods belong to the class, not the instance), they must declare their own generic type parameters if they want to be generic.
Q: Do you have to explicitly define the type when calling a generic method?
A: Usually, no. The Java compiler performs Type Inference, meaning it looks at the arguments you pass in and automatically figures out what T should be. However, you can explicitly state the type if needed, using syntax like this: GenericMethodExample.<String>printArray(strArray);.