#Generic classes and methods
AddedA type parameter lets one class or method work with many types while the compiler still checks every use. List<String> is a list that the compiler guarantees holds only strings; Map<String, Integer> maps strings to integers. You used these in Java 5 and 6, and TypeScript generics look almost the same: class Page<T>, function first<T>(items: T[]): T.
What's worth knowing now is how to write generic code, not just use it:
- A generic class or record declares its type parameters after its name:
record Page<T>(List<T> items, int number, int totalPages). Inside,Tstands for whatever type the user picks. - A generic method declares its own type parameters before the return type:
static <T> T firstOrElse(List<T> items, T fallback). The compiler infersTfrom the arguments at each call, as TypeScript does. - The diamond
new ArrayList<>()(Java 7) lets the compiler fill in the type arguments on the right from the left: no morenew HashMap<String, List<Integer>>()written twice. - Type arguments must be reference types:
List<Integer>, neverList<int>(see Generics gotchas).
The mental model: a type parameter is a blank on a form that the caller fills in, and once it's filled in (Page<Product>), the compiler checks every line against it. Before Java 5, collections held Object and you cast on every read; generics moved that cast from your code, where it could be wrong, into the compiler, which checks it.
record Page<T>(List<T> items, int number, int totalPages) {
boolean isLast() {
return number == totalPages;
}
<R> Page<R> map(Function<T, R> mapper) {
var mapped = new ArrayList<R>();
for (T item : items) {
mapped.add(mapper.apply(item));
}
return new Page<>(mapped, number, totalPages);
}
}
static <T> T firstOrElse(List<T> items, T fallback) {
return items.isEmpty() ? fallback : items.get(0);
}
void main() {
Page<String> names = new Page<>(List.of("desk", "chair", "lamp"), 2, 2);
Page<Integer> lengths = names.map(String::length);
IO.println(names + " last: " + names.isLast());
IO.println(lengths);
String first = firstOrElse(names.items(), "none");
int firstLength = firstOrElse(lengths.items(), 0);
IO.println(first + " " + firstLength + " " + firstOrElse(List.of(), "empty"));
}$ java Pages.java
Page[items=[desk, chair, lamp], number=2, totalPages=2] last: true
Page[items=[4, 5, 4], number=2, totalPages=2]
desk 4 emptyrecord Page<T>declares one type parameter.new Page<>(List.of("desk", "chair", "lamp"), 2, 2)uses the diamond: the compiler sees the variable is aPage<String>and fills inT = String.mapis a generic method inside a generic class: it has its own parameterR, the type of the result.names.map(String::length)passes a function fromStringtoInteger, so the compiler infersR = Integerand returns aPage<Integer>.- The first line prints the record with its items:
Page[items=[desk, chair, lamp], number=2, totalPages=2] last: true. The second prints the mapped page,[4, 5, 4], with the same page numbers. firstOrElseis a static generic method. Fornames.items()the compiler infersT = String, so the result can go straight into aStringwith no cast. Forlengths.items()it infersInteger, which unboxes intoint.firstOrElse(List.of(), "empty")works too:List.of()has no elements to infer from, so the compiler uses the other argument and picksT = String, returning the fallback,empty.- In TypeScript this whole file would read almost the same. The difference you'll feel is in what the compiler refuses, next.
The point of generics is that mistakes fail at compile time instead of at the line that reads the value. Here is the same bug written with a raw List, the way Java 1.4 code worked, and with a List<String>:
public class Raw {
public static void main(String[] args) {
java.util.List names = new java.util.ArrayList();
names.add("Rohit");
names.add(42);
for (Object o : names) {
String name = (String) o;
System.out.println(name.toUpperCase());
}
}
}import java.util.ArrayList;
import java.util.List;
public class Typed {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Rohit");
names.add(42);
for (String name : names) {
System.out.println(name.toUpperCase());
}
}
}$ java Raw.java
Raw.java:4: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
names.add("Rohit");
^
where E is a type-variable:
E extends Object declared in interface List
Raw.java:5: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
names.add(42);
^
where E is a type-variable:
E extends Object declared in interface List
2 warnings
ROHIT
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at Raw.main(Raw.java:7)
$ java Typed.java
Typed.java:8: error: no suitable method found for add(int)
names.add(42);
^
method List.add(String) is not applicable
(argument mismatch; int cannot be converted to String)
method List.add(int,String) is not applicable
(actual and formal argument lists differ in length)
1 error
error: compilation failed- The raw
Listaccepts anything, sonames.add(42)compiles. The compiler notices the raw type and prints an "unchecked" warning for eachadd, but warnings don't stop it: the program runs. - At run time the loop prints
ROHIT, then reaches theInteger, and the cast(String) ofails withClassCastException. The bug was theadd, but the crash is at the read, which in real code may be in another class or another day. - With
List<String>,names.add(42)is a compile error: noadd(int)fits a list of strings, so nothing runs. The bug is caught on the line that causes it. - The typed loop needs no cast:
for (String name : names)is checked by the compiler. The cast still exists in the bytecode (see Type erasure), but the compiler has proved it can't fail.
Inference usually works, but sometimes there's nothing to infer from, and you can pass the type argument yourself with a type witness: Collections.<String>emptyList(). You'll mostly see it in older code and in chained calls.
import java.util.Collections;
import java.util.List;
public class Witness {
static <T> List<T> twice(T value) {
return List.of(value, value);
}
public static void main(String[] args) {
List<String> empty = Collections.emptyList();
var alsoEmpty = Collections.<String>emptyList();
var numbers = Witness.<Number>twice(7);
System.out.println(empty + " " + alsoEmpty + " " + numbers);
numbers = List.of(1.5, 2);
System.out.println(numbers);
}
}$ java Witness.java
[] [] [7, 7]
[1.5, 2]List<String> empty = Collections.emptyList();infersT = Stringfrom the variable's type: the target type.- With
varthere's no target type, soCollections.<String>emptyList()states it. Without the witness,var alsoEmptywould be aList<Object>. Witness.<Number>twice(7)forcesT = Number, sonumbersis aList<Number>rather than theList<Integer>that inference would pick. It prints[] [] [7, 7].- Because it's a
List<Number>, the variable can later holdList.of(1.5, 2), a list mixing aDoubleand anInteger:[1.5, 2]. AList<Integer>variable couldn't.