Java 12: Generic Classes & Methods
easy⏱ 5 mincoursejava
Generic class
class Box<T> { private T value; public T get() { return value; } }. The T is a type parameter — bound at each use site: Box<String>, Box<Integer>. The compiler checks every put/get; at runtime, generics are erased to Object (see Lesson 14).
Box<String> b = new Box<>();
b.set("hi");
String s = b.get(); // no cast needed
// b.set(42); // compile error
Generic method
A method can declare its own type parameters, independent of its class: public static <T> List<T> repeat(T x, int n) {...}. Type inference usually picks T from the arguments — repeat("x", 3) infers T=String.
public static <T> void swap(T[] arr, int i, int j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Build a Pair<A, B>
Create a Pair<A, B> class with first, second, and a swap(): Pair<B, A> method. Then write a generic zip<A, B>(a: A[], b: B[]): Pair<A, B>[]. Test with Pair<string, number> and show the swap returns Pair<number, string>.
Diamond operator
Java 7+ infers the right-hand generic: Map<String, List<Integer>> m = new HashMap<>(); — no need to repeat the types. Since Java 10, var makes it even tighter: var m = new HashMap<String, List<Integer>>();.
Quiz: Generic static method
Is this legal: class Box<T> { static T identity(T x) { return x; } }? No. A static method can't use the class's type parameter (it has no instance). Declare its own: static <U> U identity(U x). Static context has no T.