Sub topic 7
Generic Methods
A generic class, like Box<T>, gets its type parameter once, when you create an object. Sometimes only one method needs that flexibility. For that case, Java has generic methods.
A generic method is a method that declares its own type parameter. The parameter belongs to that one method, not to the whole class. A generic method can live inside an ordinary class that is not generic at all.
Declaring a Generic Method
You put the type parameter in angle brackets before the return type. Here is a helper that returns the first item in a list, or a fallback value if the list is empty.
import java.util.List;
public class ListUtils {
public static <T> T firstOrDefault(List<T> list, T fallback) {
return list.isEmpty() ? fallback : list.get(0);
}
public static void main(String[] args) {
String s = firstOrDefault(List.of("a", "b"), "none");
Integer n = firstOrDefault(List.<Integer>of(), 0);
System.out.println(s); // a
System.out.println(n); // 0
}
}Read the signature from left to right:
| Part | Meaning |
|---|---|
| `public static` | Ordinary modifiers |
| `<T>` | Declares a type parameter named `T` for this method |
| `T` | The return type is whatever `T` turns out to be |
| `List<T> list, T fallback` | Both arguments use the same `T` |
The class ListUtils has no <T> of its own. Only the method does.
Type Inference for Methods
Type inference means the compiler works out the type argument for you. When you call firstOrDefault(List.of("a", "b"), "none"), the compiler sees a List<String> and a String. So it decides that T is String. You never write String in the call.
If inference ever fails, you can name the type yourself. You put it after the dot, before the method name:
String s = ListUtils.<String>firstOrDefault(List.of("a"), "none");You will rarely need this. The second call in main, List.<Integer>of(), shows one such case. An empty List.of() gives the compiler no clue about the element type, so we name it.
The Compiler Still Checks Types
Because both arguments share T, the compiler can catch mistakes:
// String s = ListUtils.firstOrDefault(List.of("a"), 5);
// compile error: the result is not a StringGeneric Methods vs. Generic Classes
| Row | Generic class | Generic method |
|---|---|---|
| Where `<T>` goes | After the class name | Before the return type |
| Scope of `T` | The whole class | One method |
| When `T` is chosen | When you create an object | Each time you call the method |
Each call can pick a different T. In main above, one call used String and the next used Integer.
Exercise
Write a static generic method lastOf that takes a List<T> and returns its last element. Where does <T> go?
Show answer
public static <T> T lastOf(List<T> list) { return list.get(list.size() - 1); } The <T> goes after static and before the return type T.
Exercise
In the call firstOrDefault(List.of(1, 2), 9), what type does the compiler infer for T?
Show answer
Integer. The list is a List<Integer>, and the int 9 is autoboxed to Integer.