Sub topic 7
Generic Methods
You have already written a generic class, such as Box<T>. In that class, the type parameter T belongs to the whole class. Sometimes you only need a type parameter for one method, and the class itself does not need to be generic. Generic methods cover that case.
A generic method is a method that declares its own type parameter. A type parameter is a placeholder name, like T, that stands for a real type such as String or Integer. Each time someone calls the method, the placeholder is filled in with a real type.
Why Generic Methods Matter
Suppose you want a helper that returns the first item of a list, or a fallback value if the list is empty. Without generics, you would need one version for String, another for Integer, and so on. You could also return Object, but then every caller would need a cast. A cast is code like (String) x that tells the compiler to treat a value as a certain type. A wrong cast only fails when the program runs.
A generic method lets you write the helper once. The compiler still checks every call.
The Syntax
The type parameter goes in angle brackets before the return type:
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.of(), 0);
System.out.println(s); // a
System.out.println(n); // 0
}
}Here is what each part of the method header means:
| Part | Meaning |
|---|---|
| `public static` | Normal modifiers |
| `<T>` | Declares a type parameter named `T` for this method only |
| `T` (return type) | The method returns a value of type `T` |
| `List<T> list` | The first argument is a list of `T` |
| `T fallback` | The second argument is also a `T` |
The <T> must come after the modifiers and before the return type. If you leave it out, the compiler looks for a real class named T and reports "cannot find symbol".
Type Inference: The Compiler Fills in T
Notice that the calls above never say what T is. The compiler works it out from the arguments. This is called type inference: the compiler works out a type that you did not write.
In firstOrDefault(List.of("a", "b"), "none"):
- The first argument is a
List<String>, soTmust beString. - The second argument,
"none", is aString. That matches. - The method returns
T, which isString, so you can assign the result to aStringwithout a cast.
The second call, firstOrDefault(List.of(), 0), is interesting. List.of() on its own has no items to look at. The compiler still uses the other argument, 0, which becomes an Integer. It also uses the target variable Integer n. So it picks T = Integer for both the method and List.of().
When inference says no
The compiler rejects a call when the types cannot agree:
// Integer x = ListUtils.firstOrDefault(List.of(1, 2), "none");
// compile error: List<Integer> needs T = Integer, but "none" is a StringThis is the safety you want. The mistake shows up while you compile, not as a crash later.
A Generic Method That Returns Nothing
Generic methods do not have to return T. This method swaps two items in any array of objects:
public class ArrayTools {
public static <T> void swap(T[] items, int i, int j) {
T temp = items[i];
items[i] = items[j];
items[j] = temp;
}
public static void main(String[] args) {
String[] names = {"Ada", "Linus", "Grace"};
swap(names, 0, 2);
System.out.println(String.join(", ", names)); // Grace, Linus, Ada
Integer[] nums = {1, 2, 3};
swap(nums, 0, 1);
System.out.println(nums[0] + " " + nums[1]); // 2 1
}
}Inside the method, T temp is a local variable of the placeholder type. The method does not know or care what T really is. It only moves values around.
Generic Methods Inside Generic Classes
A generic class can also have generic methods. The method can use the class's T and add a new type parameter of its own. In the example below, map turns a Box<T> into a Box<R>, where R is any type the caller picks.
Function<T, R> is a built-in Java interface for "something that takes a T and gives back an R". String::length is a short way to write such a function.
import java.util.function.Function;
public class Box<T> {
private final T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
public <R> Box<R> map(Function<T, R> change) {
return new Box<>(change.apply(value));
}
public static void main(String[] args) {
Box<String> word = new Box<>("hello");
Box<Integer> length = word.map(String::length);
System.out.println(length.get()); // 5
}
}T was fixed when the box was created (String). R is picked fresh for each call to map (Integer here).
Static methods need their own type parameter
A static method belongs to the class itself, not to any one object. So it cannot use the class's T, because T only has a value for a particular object such as Box<String>.
public class Box<T> {
// static T make(T v) { ... } // compile error
static <U> Box<U> of(U v) { // works: declares its own U
return new Box<>(v);
}
private final T value;
Box(T value) { this.value = value; }
}Do not reuse the class's name
If a method inside Box<T> declares its own <T>, the new T hides the class's T. They become two unrelated types that share a name. The code compiles, but it is confusing and often wrong. Pick a different letter, such as R or U.
Giving the Type Explicitly
You can also tell the compiler which type to use. You write it in angle brackets just before the method name. This is called a type witness:
import java.util.Collections;
import java.util.List;
public class WitnessDemo {
public static void main(String[] args) {
List<String> empty = Collections.<String>emptyList();
String s = ListUtils.<String>firstOrDefault(List.of("x"), "none");
System.out.println(empty.size() + " " + s); // 0 x
}
}To run this, keep ListUtils.java from earlier in the same folder. Note that a type witness needs something written before the dot: the class name for a static method, or this. for an instance method. Plain <String>firstOrDefault(...) does not compile.
You rarely need a witness in modern Java. It is useful when inference picks a type you did not expect, or when you want the call to be easier to read.
A Surprise: Inference Can Pick a Wide Type
Look at this method:
public class Pick {
public static <T> T pick(T a, T b) {
return a;
}
public static void main(String[] args) {
Object o = pick("hello", 42); // compiles!
System.out.println(o); // hello
}
}Why does a String and an Integer work together? The compiler looks for a type that both values belong to. Both are Object, so T can be a shared parent type. But String s = pick("hello", 42); fails, because the shared type is not String. If you want to limit which types T may be, you need bounds. A later chapter covers them.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `<T>` placed after the return type | Syntax error | Write `public static <T> T name(...)` |
| Forgetting `<T>` entirely | "cannot find symbol T" | Declare `<T>` before the return type |
| Static method using the class's `T` | Compile error | Declare a new type parameter on the method |
| Passing `int[]` to a `T[]` method | Compile error | Use `Integer[]` |
| Method's `<T>` hides the class's `T` | Confusing bugs | Use a different letter |
| Calling `<String>method()` without a qualifier | Syntax error | Write `ClassName.<String>method()` |
Exercise
Write a static generic method lastOrDefault that returns the last item of a List<T>, or a fallback if the list is empty. What does lastOrDefault(List.of(4, 7, 9), 0) return?
Show answer
public static <T> T lastOrDefault(List<T> list, T fallback) { return list.isEmpty() ? fallback : list.get(list.size() - 1); } The call infers T as Integer and returns 9.
Exercise
Inside class Box<T>, why does static T make(T v) fail to compile, and how do you fix it?
Show answer
A static method belongs to the class, not to one Box object, so the class's T has no value there. Declare the method's own type parameter: static <U> Box<U> make(U v) { return new Box<>(v); }.
Exercise
Does String s = ListUtils.firstOrDefault(List.of(1, 2), "none"); compile? Explain.
Show answer
No. List<Integer> forces T to be Integer, but "none" is a String and the target variable is a String. No single T fits every part of the call, so the compiler reports an error.