Generics
Type parameters for classes and methods, bounded types, wildcards and the PECS rule, type erasure and its consequences, and generic design tips.
Generics let you write classes and methods that work with any type while keeping compile-time type safety. Before Java 5, a List held Objects: you cast on every read and found mistakes at runtime. With List<String>, the compiler rejects an Integer and no casts are needed.
Generic classes and methods
public class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T get() { return value; }
public <R> Box<R> map(Function<? super T, ? extends R> f) { return new Box<>(f.apply(value)); }
}
Box<String> b = new Box<>("hi"); // diamond operator infers <String>
Box<Integer> len = b.map(String::length);
// Generic method: the type parameter is declared before the return type
public static <T> T firstOrDefault(List<T> list, T fallback) {
return list.isEmpty() ? fallback : list.get(0);
}
String s = firstOrDefault(names, "none"); // T inferred as StringConvention: T (type), E (element), K/V (key/value), R (result).
Bounded type parameters
Restrict the type so you can call its methods:
// T must be comparable to itself
public static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T x : items) if (x.compareTo(best) > 0) best = x;
return best;
}
// Multiple bounds: a class first, then interfaces
static <T extends Number & Comparable<T>> T clampMax(T a, T b) { return a.compareTo(b) > 0 ? b : a; }Invariance: why List<Integer> is not a List<Number>
Arrays are covariant (Integer[] is a Number[]), which is unsafe:
Number[] nums = new Integer[1];
nums[0] = 3.14; // compiles, throws ArrayStoreException at runtimeGenerics are invariant to prevent this at compile time:
List<Integer> ints = new ArrayList<>();
List<Number> nums = ints; // compile error — otherwise you could add a Double to intsWildcards and PECS
Wildcards make APIs flexible where invariance is too strict.
| Wildcard | Meaning | You can | Use when the collection is a… |
|---|---|---|---|
List<? extends Number> | Some unknown subtype of Number | Read as Number; can't add (except null) | Producer (you take items out) |
List<? super Integer> | Some unknown supertype of Integer | Add Integers; read only as Object | Consumer (you put items in) |
List<?> | Unknown type | Read as Object | You don't care about the type |
PECS: Producer Extends, Consumer Super.
// Sum any list of numbers: the list produces values
static double sum(List<? extends Number> xs) {
double total = 0;
for (Number n : xs) total += n.doubleValue();
return total;
}
sum(List.of(1, 2, 3)); sum(List.of(1.5, 2.5)); // both work
// Copy from a producer into a consumer (like Collections.copy)
static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (T item : src) dest.add(item);
}
List<Object> sink = new ArrayList<>();
copy(sink, List.of("a", "b")); // T = String
// Comparator<? super T> accepts a comparator for a supertype
static <T> void sort(List<T> list, Comparator<? super T> c) { ... }Type erasure
Generics exist only at compile time. The compiler checks types, inserts casts, and then erases type parameters to their bounds (T → Object, T extends Comparable<T> → Comparable) in the bytecode. List<String> and List<Integer> are the same class at runtime.
Consequences:
new T(); // ✗ can't instantiate a type parameter
new T[10]; // ✗ can't create generic arrays
if (obj instanceof List<String>) {} // ✗ can't check parameterised types at runtime
static T cache; // ✗ static fields can't use the class's T
void f(List<String> a) {} void f(List<Integer> a) {} // ✗ same erasure: clash
List<int> // ✗ primitives not allowed: use List<Integer> (boxing cost)Workarounds: pass a Class<T> token (clazz.getDeclaredConstructor().newInstance()), or a Supplier<T> factory; use Array.newInstance for arrays; libraries like Jackson capture full types with TypeReference<List<User>> (a subclass preserves generic info in its signature).
Recursive generics
// "Comparable to itself" and fluent builders that return the subclass type
abstract class Builder<T extends Builder<T>> {
protected abstract T self();
T name(String n) { /* ... */ return self(); }
}
class PizzaBuilder extends Builder<PizzaBuilder> {
protected PizzaBuilder self() { return this; }
PizzaBuilder cheese() { return this; }
}
new PizzaBuilder().name("x").cheese(); // name() returns PizzaBuilder, so cheese() is availableEnum<E extends Enum<E>> uses the same trick.
- Generics give compile-time type safety without casts.
- Bounds (T extends X) let you call X's methods on T.
- Generics are invariant; use wildcards for flexibility — Producer Extends, Consumer Super.
- Type erasure removes type arguments at runtime: no new T, no generic arrays, no instanceof List of String.
- Avoid raw types; use Class tokens or Suppliers when you need the runtime type.
QWhat is type erasure and what are its limitations?medium
The compiler uses generic types for checking and then replaces type parameters with their bounds (usually Object) in bytecode, inserting casts where needed. This kept compatibility with pre-generics code. As a result you cannot instantiate T, create generic arrays, use instanceof with parameterised types, overload methods that differ only by type argument, or use primitives as type arguments.
QExplain PECS.medium
Producer Extends, Consumer Super. If a parameterised collection supplies values to your method, declare it with ? extends T so subtypes are accepted. If your method puts values into it, declare it with ? super T so supertype collections are accepted. Collections.copy(List of ? super T dest, List of ? extends T src) is the canonical example.