Generics let you write a type once and keep List<String> distinct from List<Integer> at compile time. The compiler inserts casts and rejects list.add(1) on a List<String>.
Mental model: type parameters are a compile-time proof. At runtime, on the HotSpot LTS JDKs, those proofs are erased. A List<String> is a List. The JVM will not stop you if you cheat with raw types or unchecked casts.
Class<T> token or a factory). Arrays of T (see reifiability). Performance-critical primitive bags (specialized collections or arrays).Never use raw types (List without <?> or a parameter) in new code. Raw types disable checking for that expression and are a heap-pollution vector.
class Box<T> { private T value; T get(); void set(T v); }
class NumberBox<T extends Number> { double asDouble() { return value.doubleValue(); } }
static <T> T first(List<T> xs) { return xs.get(0); }
static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
class Foo<T>. On methods: <T> T m(...) before the return type.T extends Number is an upper bound. T can be Number or a subtype. You may call Number methods on T.T extends Number & Comparable<T> — class first, then interfaces.T super Foo is illegal). Lower bounds live on wildcards: ? super Foo.new ArrayList<>() infers from the left-hand type (Java 7+). On var, inference uses the constructor arguments (Java 10+).PECS: Producer extends, Consumer super. (Effective Java.)
| Wildcard | You can | You cannot | Use when |
|---|---|---|---|
List<T> | get T, add T | — | You produce and consume |
List<? extends T> | get T (or subtype as T) | add (except null) | The list is a producer |
List<? super T> | add T | get as T (only Object) | The list is a consumer |
List<?> | get Object | add (except null) | You only care that it is a list |
void copy(List<? extends Number> src, List<? super Number> dest) {
for (Number n : src) dest.add(n);
}
copy(List.of(1, 2.5), new ArrayList<Object>());
List<Integer> is not a List<Number> (invariance). It is a List<? extends Number>. That is why PECS exists.
When not to wildcard: return types. Returning List<? extends Foo> makes the caller miserable. Return a concrete List<Foo> (or a copy).
The compiler erases type arguments to their bounds (Object if unbound). It inserts casts at get sites. Overload resolution and the JVM see the erased signature.
// These two cannot coexist in one class
void f(List<String> a) {}
void f(List<Integer> a) {} // error: both erase to f(List)
List<?> (unbounded wildcard is reifiable), arrays of reifiable types.List<String>, T, List<? extends Number>. You cannot write new T[] or a fully checked instanceof List<String>.instanceof List<String> does not compile. instanceof List<?> does.new List<String>[n] is illegal. new List<?>[n] is legal and still unpleasant. Prefer List<List<String>>.Type tokens: when you must construct or cast T at runtime, take a Class<T> (or a TypeReference for nested generics, as Jackson does).
public static <T> T read(String json, Class<T> type) { /* mapper */ }
User u = read(body, User.class);
Heap pollution means a variable of type List<String> might actually contain an Integer because someone used raw types or unchecked casts.
List raw = new ArrayList<String>(); List<Integer> ints = raw; // unchecked warning ints.add(1); List<String> strings = raw; String s = strings.get(0); // ClassCastException later
Generic varargs (<T> void of(T... xs)) create an array of a non-reifiable type — the compiler warns. @SafeVarargs (on static/final/private methods) asserts you do not leak or write that array unsafely. Prefer List<T> in public APIs (List.of is carefully implemented).
// Incorrect — too rigid void addAll(List<Number> dest, List<Number> src); // Correct — PECS void addAll(List<? super Number> dest, List<? extends Number> src); // Incorrect — wildcard return List<? extends User> findAll(); // Correct List<User> findAll(); // Incorrect — raw List ids = new ArrayList(); // Correct List<String> ids = new ArrayList<>();
Collections.copy, Comparable (T extends Comparable<? super T>), and Comparator are PECS applied in the JDK. Copy that style.
@SuppressWarnings("unchecked") must be as small as possible and justified.T.class exists — it does not.Class<List<String>> — you cannot write that meaningfully; Class objects are reifiable, lists of strings are not. Use Class<List> plus extra care, or a TypeReference.toArray: prefer list.toArray(new String[0]) or toArray(String[]::new) (Java 11).?.T extends Foo when you need Foo’s methods. Comparable<? super T> for ordering.new T[], no instanceof List<String>, no overload on type arguments.Class<T> when the implementation must reify T.~ Good luck with your revision! ~