Java › Generics
How do you write a generic method (as opposed to a generic class), and how does the compiler infer the type parameter from the arguments passed at a call site?
IntermediateAnswer
A generic method declares its own type parameter(s) in angle brackets immediately before the return type (independent of whether the enclosing class itself is generic), and the compiler performs type inference at each call site, examining the actual argument types passed to determine what the type parameter should be, without requiring you to explicitly specify it (though you can, via ClassName.<Type>methodName(...) syntax, in rare cases where inference is ambiguous or insufficient).
public class Utils {
public static <T> T firstNonNull(T a, T b) {
return a != null ? a : b;
}
}
String result = Utils.firstNonNull(null, "default"); // T inferred as String from the arguments
Integer num = Utils.firstNonNull(5, 10); // T inferred as Integer
// Explicit type witness syntax, rarely needed but available
String explicit = Utils.<String>firstNonNull(null, "default");Real-world example A generic utility method like Collections.emptyList() infers its type parameter entirely from the context where its return value is assigned or used (like List<String> empty = Collections.emptyList()), letting the same single generic method definition serve every possible element type without any explicit type argument needed at typical call sites.