Generic Methods & Type Parameter Inference
1Concept
A generic method introduces its own type parameters before the return type (`public <T> void method(T arg)`). The compiler infers the exact type argument automatically from the method arguments and assignment context.
2Architecture Diagram
Generic Method Declaration:
public static <T extends Comparable<T>> T findMax(T a, T b)
^^ Type Parameter Bound ^^ Return Type3Code Example
Core Java
public class GenericMethodsDemo {
public static <T extends Comparable<T>> T findMax(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
public static void main(String[] args) {
String maxStr = findMax("Apple", "Zebra");
Integer maxInt = findMax(42, 99);
Double maxDbl = findMax(3.14, 2.71);
System.out.println("Max String: " + maxStr);
System.out.println("Max Integer: " + maxInt);
System.out.println("Max Double: " + maxDbl);
}
}4Expected Output
Max String: Zebra Max Integer: 99 Max Double: 3.14
5Key Takeaways
- ✓Type parameter `<T>` must appear immediately before the return type in generic method declarations.
- ✓Static methods CANNOT use class-level generic type parameters; they must declare their own.
- ✓Bounded types (`<T extends Comparable<T>>`) restrict parameters to types supporting specific operations.