Glossary · Java
Generics
Also known as: java generics, type parameters, type erasure, wildcards
A Java feature that lets classes and methods take type parameters, such as List<String>, so the compiler catches type errors and you avoid casts.
Example
// Generic method: works for any Comparable type
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.getFirst();
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
Integer top = max(List.of(3, 9, 4)); // no cast needed
PECS: wildcards in one line
Producer extends, Consumer super:
void copy(List<? extends Number> src, List<? super Number> dst) { dst.addAll(src); }
Type erasure
Type parameters exist only at compile time. At runtime List<String> and List<Integer> are both just List, so you cannot write new T() or instanceof List<String>.