Java Programming
Java Generics: Type Parameters, Bounds, Wildcards and Erasure
Intermediate7 min readUpdated
Generics let you write a class or method once and use it safely with many types, moving cast errors from run time to compile time. This guide explains how to declare and use type parameters, how bounds and wildcards express what a method needs, why List<Dog> is not a List<Animal>, what type erasure does and does not allow, and the idioms — PECS, generic methods, type tokens — that make generic code readable.
What you will learn
- Declare generic classes, interfaces and methods with meaningful type parameters
- Apply upper and lower bounds and the PECS rule to wildcard parameters
- Explain invariance and why arrays behave differently from generic collections
- Describe type erasure and work around its limits with class tokens and helper methods
- Recognise raw types and unchecked warnings as bugs waiting to happen
Before generics arrived in Java 5, a List held Object, every retrieval needed a cast, and a wrong cast surfaced as a ClassCastException far from the code that caused it. Generics move that check to the compiler: List<String> can only contain strings, and get returns a String with no cast. The mechanics are straightforward until you meet wildcards and erasure, which is where most developers stop understanding what they are writing. This guide gets you through both. Examples target Java 21.
Generic classes and interfaces
A type parameter is a placeholder for a type, declared in angle brackets after the class name and used inside the class wherever a type would appear:
public final class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A first() { return first; }
public B second() { return second; }
public <C> Pair<A, C> withSecond(C newSecond) { // generic method inside a generic class
return new Pair<>(first, newSecond);
}
}
Pair<String, Integer> p = new Pair<>("age", 42);
Integer age = p.second(); // no cast
Pair<String, Boolean> q = p.withSecond(true);
The diamond <> on new Pair<>(...) asks the compiler to infer the arguments from the target type, so you write them once. Conventionally, type parameters are single capital letters: T for a type, E for an element, K/V for key and value, R for a result. Longer names such as Request are legal and sometimes clearer in complex signatures.
Type parameters must be reference types. List<int> does not compile; you write List<Integer> and pay the boxing cost, which is why the streams API has IntStream and why java.util.function has IntPredicate, ToLongFunction and other primitive specialisations.
Generic interfaces work the same way. Comparable<T>, Iterable<T>, Function<T, R> and Map<K, V> are the ones you implement or accept most often, and a class can fix the parameter on implementation — class Version implements Comparable<Version> — which is what lets compareTo take a Version rather than an Object.
Generic methods
A method can introduce its own type parameter, declared before the return type. This is the right choice for static utilities and for any method whose type relationship is independent of the enclosing class:
public static <T> List<T> repeat(T value, int times) {
List<T> result = new ArrayList<>(times);
for (int i = 0; i < times; i++) result.add(value);
return result;
}
public static <T, R> List<R> mapAll(List<T> input, Function<? super T, ? extends R> fn) {
List<R> out = new ArrayList<>(input.size());
for (T item : input) out.add(fn.apply(item));
return out;
}
List<String> xs = repeat("x", 3); // T inferred as String
List<Integer> lengths = mapAll(xs, String::length); // T = String, R = Integer
Inference nearly always finds the arguments. When it fails — typically with an empty collection or a chained call whose target type is unknown — you can state them explicitly with a type witness: Collections.<String>emptyList().
Bounded type parameters
An unbounded T is effectively Object inside the method: you can store it and return it, but call nothing on it. A bound restricts the parameter and unlocks the bound's methods:
public static <T extends Comparable<? super T>> T max(Collection<? extends T> items) {
Iterator<? extends T> it = items.iterator();
T best = it.next();
while (it.hasNext()) {
T candidate = it.next();
if (candidate.compareTo(best) > 0) best = candidate; // compareTo is available
}
return best;
}
T extends Comparable<? super T> reads as "T can be compared with itself or with a supertype of itself". The ? super T matters: if Employee implements Comparable<Employee> and Manager extends Employee, then max(List<Manager>) compiles because Manager is comparable through the inherited Comparable<Employee>. With a plain Comparable<T> bound the call would only compile by inferring T as Employee, so max would hand back an Employee and you would be casting again. Multiple bounds use &: <T extends Number & Comparable<T>>, with at most one class and any number of interfaces.
The keyword is always extends, even for interfaces; there is no implements in a bound.
Invariance and why arrays are different
Generic types are invariant: List<Manager> is not a subtype of List<Employee>, even though Manager is a subtype of Employee. The reason is soundness. If the assignment were allowed:
List<Manager> managers = new ArrayList<>();
List<Employee> employees = managers; // hypothetically allowed
employees.add(new Contractor()); // legal on a List<Employee>...
Manager m = managers.get(0); // ...and now this explodes
Arrays made the opposite choice: Manager[] is a subtype of Employee[] (covariance), and the JVM checks every store at run time, throwing ArrayStoreException if a Contractor is put into what is really a Manager[]. Generics moved the check to compile time and gave up covariance to do so. That is also why you cannot create a generic array — new T[10] and new List<String>[3] are illegal — because the run-time check would need a type that erasure has removed.
Wildcards and the PECS rule
Invariance is safe but restrictive: a method printAll(List<Employee>) would refuse a List<Manager>. Wildcards restore flexibility on the use side, by stating what the method needs.
List<? extends Employee>— a list of Employee or some subtype. You can read elements asEmployee. You cannot add anything exceptnull, because the actual element type might beManagerand you might be holding aContractor.List<? super Manager>— a list of Manager or some supertype. You can add aManager(it fits whatever the actual type is). Reading gives youObject, because the actual type might beEmployeeorObject.List<?>— a list of something. Read asObject, add nothing.
The mnemonic is PECS: Producer Extends, Consumer Super. If the parameter produces values you read, use extends; if it consumes values you put in, use super; if both, use the exact type.
// Copy from a producer into a consumer
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (T item : src) dest.add(item);
}
List<Employee> staff = new ArrayList<>();
List<Manager> mgrs = List.of(new Manager("Ada"), new Manager("Grace"));
copy(staff, mgrs); // dest is a super of Manager, src produces Managers
The JDK's own signatures follow this: Collections.copy(List<? super T> dest, List<? extends T> src), Stream.map(Function<? super T, ? extends R>), Collection.addAll(Collection<? extends E>). When you see ? super T on a Comparator or Consumer, it is PECS at work — a Comparator<Object> can compare employees, so sort(List<T>, Comparator<? super T>) accepts it.
Wildcards belong in method parameters. Return types should be concrete: a method returning List<? extends Shape> forces every caller to deal with the wildcard for no benefit.
Type erasure
Generics are a compile-time feature. After checking, the compiler erases type parameters: an unbounded T becomes Object, a bounded T extends Number becomes Number, and casts are inserted at call sites. List<String> and List<Integer> are the same class at run time. This was the price of backward compatibility with pre-generic bytecode, and it has consequences:
| You cannot write | Because |
|---|---|
new T() | No class to instantiate at run time |
new T[n] | Array needs a run-time element type |
obj instanceof List<String> | The parameter no longer exists; instanceof List<?> is allowed |
catch (T e) | Exception types must be reifiable |
Overloads f(List<String>) and f(List<Integer>) | Same erased signature |
static T field | Statics are shared by all parameterisations |
The standard work-around for "I need the class at run time" is a type token: pass Class<T> explicitly.
public static <T> T firstOfType(List<?> items, Class<T> type) {
for (Object item : items) {
if (type.isInstance(item)) return type.cast(item); // safe, checked cast
}
return null;
}
Integer n = firstOfType(List.of("a", 7, 2.0), Integer.class); // 7
Class<T>.cast and isInstance give you a checked cast without an unchecked warning. Frameworks such as Jackson and Spring use this idiom, and extend it with ParameterizedTypeReference/TypeReference subclasses to capture a full List<Foo> type through reflection on an anonymous subclass — the one place erasure leaves the full signature intact.
Erasure also introduces bridge methods: when Version implements Comparable<Version>, the compiler generates a hidden compareTo(Object) that casts and delegates, so that code calling through the erased interface still works. You will only notice them in stack traces and reflection.
Raw types and unchecked warnings
A raw type is a generic type used without arguments: List list = new ArrayList();. It exists only so that pre-Java 5 code compiles, and using it disables the type checks for everything that touches it. Every raw type in a modern codebase is a latent ClassCastException.
An unchecked warning means the compiler could not prove a cast or call is type-safe — typically a cast to a parameterised type, such as (List<String>) obj. Never suppress one with @SuppressWarnings("unchecked") without a comment proving why it is safe, and put the annotation on the smallest possible scope (a local variable, not the class). The Class<T>.cast idiom above avoids the warning entirely for single-type casts.
A specific, common case: generic varargs. List<String>... lists creates an array of a generic type, which the compiler warns about at every call site. If the method only reads the array, annotate it with @SafeVarargs (allowed on static, final and private methods) and the warning disappears at call sites.
Recursive bounds and fluent builders
<T extends Comparable<T>> is a recursive type bound: the parameter appears in its own bound. The same trick lets a builder base class return the concrete subclass type from its fluent methods:
abstract class Builder<B extends Builder<B>> {
protected String name;
public B name(String name) { this.name = name; return self(); }
protected abstract B self();
}
final class UserBuilder extends Builder<UserBuilder> {
private String email;
public UserBuilder email(String email) { this.email = email; return this; }
@Override protected UserBuilder self() { return this; }
public User build() { return new User(name, email); }
}
User u = new UserBuilder().name("Ada").email("[email protected]").build();
// Without the recursive bound, name() would return Builder and email() would not exist
Use this sparingly; it is powerful but hard to read, and a single concrete builder often serves better.
Common mistakes
Raw types. new ArrayList() or Map map throw away the checks. Add the type arguments; use the diamond so you type them once.
Returning wildcards. List<? extends Number> compute() pushes complexity onto every caller. Return List<Number> or a specific type.
Wildcards on both sides. void merge(List<? extends T> a, List<? extends T> b) cannot add anything from b into a. When a parameter is both read and written, use the plain type parameter.
Assuming List<String> survives to run time. Deserialisation, reflection and instanceof see only List. Use type tokens or explicit conversions.
Mixing arrays and generics. T[] fields, new ArrayList<String>[n] and List<String>[] all produce warnings or errors. Prefer List<List<String>>.
Overusing Object to avoid generics. A method that takes Object and casts inside is the pre-generics world with extra steps. Introduce a type parameter.
Bounding with Comparable<T> alone. Rejects subclasses of a comparable class. Use Comparable<? super T>.
Key takeaways
- Type parameters move cast failures to compile time; declare them on classes, interfaces or individual methods, and let the diamond and inference fill in arguments.
- Bounds (
T extends X) make the bound's methods callable;Comparable<? super T>is the correct bound for sortable elements. - Generic types are invariant. Use
? extendsfor parameters you read from and? superfor parameters you write to (PECS); return concrete types. - Erasure removes type arguments at run time, so
new T(), generic arrays andinstanceof List<String>are impossible; pass aClass<T>token when you need the type. - Raw types and unsuppressed unchecked warnings are bugs in waiting; fix them rather than silencing them.
- Arrays are covariant and checked at run time; collections are invariant and checked at compile time. Prefer collections in generic code.
Sources and further reading
Frequently asked questions
- Why can I not assign a List<Dog> to a List<Animal>?
- Because generic types are invariant. If the assignment were allowed, code holding the List<Animal> could add a Cat to what is really a list of dogs, and the failure would surface later as a ClassCastException somewhere unrelated. Use List<? extends Animal> when you only need to read animals from the list.
- What does 'type erasure' mean?
- The compiler checks generic types and then removes them from the bytecode, replacing type parameters with their bound (usually Object) and inserting casts where needed. At run time a List<String> and a List<Integer> are the same class. That is why you cannot write new T(), T[] or instanceof List<String>.
- What is the difference between List<Object> and List<?>?
- List<Object> is a list that may hold any object and that you may add anything to; only a List<Object> can be assigned to it. List<?> is a list of some unknown specific type: any List<X> can be assigned to it, but you can only add null because the compiler does not know what X is.
- Should I use T extends Comparable<T> or T extends Comparable<? super T>?
- The second form is more flexible. If a class Employee implements Comparable<Employee> and Manager extends Employee, then Manager is comparable through its superclass's implementation. Comparable<? super T> accepts that; Comparable<T> alone rejects a List<Manager>.