Java generics series: 1. Generic classes, methods, bounded types · 2. Wildcards and PECS · 3. Type erasure and type tokens
Before Java 5, collections only held Object: putting in the wrong type still compiled, then blew up with a ClassCastException at runtime, far from the line that caused it. Generics put types into class and method signatures so the compiler catches that mistake at compile time. After this post you can write generic classes, generic methods and bounded types, and explain why a List<Integer> isn’t a List<Number>.
You only need basic OOP and Collections. Part 2 covers wildcards and the PECS rule, and part 3 covers type erasure and how Jackson gets the type back at runtime.
At a glance:
flowchart TD
G[Generics] --> CT["Type errors: at compile time"]
G --> GC["Generic class: per object"]
G --> GM["Generic method: per call"]
GM --> SM["Static method: declares own T"]
G --> B["Bound: T extends X"]
G --> INV["Invariant: List#lt;Integer#gt; ≠ List#lt;Number#gt;"]
INV -.->|unlike| ARR["Covariant arrays: ArrayStoreException"]
V["var + new ArrayList#lt;#gt;()"] -.->|trap| OB["ArrayList#lt;Object#gt;"]
1. Why generics
Key idea: without generics, a wrong-type insert only shows up at runtime. With generics, the compiler blocks it while you type and inserts the casts for you.
Old-style code with a raw type (a generic type written without <>, treated as holding Object):
List names = new ArrayList();
names.add("Alice");
names.add(42); // the compiler doesn't object
for (Object o : names) {
String s = (String) o; // ClassCastException on the second element
System.out.println(s.toUpperCase());
}
With generics:
List<String> names = new ArrayList<>();
names.add("Alice");
// names.add(42); // compile error: int is not a String
String first = names.get(0); // no cast needed
Generics give you three things:
- Earlier errors: type mistakes move from runtime (when a customer is using the app) to compile time (when you’re writing the code).
- No manual casts: the compiler inserts them, and they can’t fail as long as the code compiles without unchecked warnings.
- Controlled reuse: one
Box<T>, oneRepository<T, ID>, onesortfor anything comparable, instead of copy-pasting code or falling back toObjectand losing the type.
Point 2 is worth remembering: generics don’t make code faster or “safer” at the bytecode level. The casts are still there; the compiler just generates them (see part 3, on type erasure).
2. Generic classes and generic methods
Key idea: put the type parameter on the class when the type is part of the object’s state; put it on the method when the type only matters for one call.
2.1. Generic classes
The type parameter is declared after the class name and used like any other type inside the class:
public final class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T get() { return value; }
public void set(T value) { this.value = value; }
// a generic method inside a generic class: it adds its own type parameter R
public <R> Box<R> map(Function<? super T, ? extends R> mapper) {
return new Box<>(mapper.apply(value));
}
}
Box<String> name = new Box<>("hello");
Box<Integer> length = name.map(String::length); // Box[5]
Four terms to keep straight:
Tinclass Box<T>is a type parameter.StringinBox<String>is a type argument.Box<String>is a parameterized type;Box(no<>) is a raw type.new Box<>(...)uses the diamond operator (Java 7): the compiler infers the type argument from the left-hand side.
Multiple type parameters are separated by commas: Map<K, V>, Pair<A, B>.
2.2. Generic methods
A generic method declares its own type parameters, placed before the return type. The enclosing class may or may not be generic:
public final class Lists {
private Lists() {}
public static <T> T firstOrNull(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
}
String s = Lists.firstOrNull(List.of("a", "b")); // T is inferred as String
String t = Lists.<String>firstOrNull(List.of("x")); // explicit type witness
The compiler usually works out T itself (type inference) from the arguments and from the type the result is assigned to. The type witness Lists.<String>firstOrNull(...) is rarely needed, mainly when inference is ambiguous.
The printArray example and why it rejects primitive arrays
A generic method you’ll see in every beginner course: print the elements of an array of any type.
public static <T> void printArray(T[] arr) {
for (T e : arr) System.out.print(e + " ");
System.out.println();
}
printArray(new String[] {"Alice", "Bob"}); // Alice Bob
printArray(new Integer[] {1, 2, 3}); // 1 2 3
2.3. Naming conventions
Type parameters are single upper-case letters, so they’re never confused with real classes: T (Type), E (Element), K/V (Key/Value), R (Result). A longer name is fine when it has a clear domain meaning (ID in JpaRepository<T, ID>), as long as it doesn’t clash with an actual class.
Full convention table with JDK examples
| Name | Usual meaning | JDK example |
|---|---|---|
T |
Type | Optional<T>, Supplier<T> |
E |
Element | List<E>, Set<E> |
K, V |
Key, Value | Map<K, V> |
R |
Result (return type) | Function<T, R> |
N |
Number | rare |
S, U |
second, third type | BiFunction<T, U, R> |
A common slip: the diamond infers the type argument from the left-hand side. With var list = new ArrayList<>(); there’s no type on the left, so you get an ArrayList<Object>, and both list.add(1); list.add("oops"); compile. With var, put the type on the right: var list = new ArrayList<String>();.
3. Bounded type parameters
Key idea: a plain T only lets you call Object’s methods. A bound <T extends X> requires T to be a subtype of X, and in exchange you can call X’s methods.
// T must be Number or a subclass -> doubleValue() is available
static <T extends Number> double sumOf(List<T> values) {
double total = 0;
for (T v : values) total += v.doubleValue();
return total;
}
- The keyword is always
extends, even when the bound is an interface (<T extends Comparable<T>>). - Multiple bounds use
&, with at most one class, and it comes first:<T extends Number & Comparable<T>>. - Recursive bound: the bound mentions
Titself, as inEnum<E extends Enum<E>>or anything that compares values.
A proper max uses <T extends Comparable<? super T>>, not Comparable<T>, so it also accepts types that inherit compareTo from a parent.
The full max method and why Comparable<T> rejects LocalDate
The same shape as Collections.max:
static <T extends Comparable<? super T>> T max(Collection<? extends T> items) {
Iterator<? extends T> it = items.iterator();
T best = it.next(); // throws NoSuchElementException if empty
while (it.hasNext()) {
T candidate = it.next();
if (candidate.compareTo(best) > 0) best = candidate;
}
return best;
}
4. Invariance: why List<Integer> isn’t a List<Number>
Key idea: if a List<Integer> were a List<Number>, you could slip a Double into a list of integers. So generics are invariant (no subtyping by type argument), while arrays are covariant and pay with runtime checks.
List<Integer> ints = new ArrayList<>(List.of(1, 2));
// List<Number> nums = ints; // compile error: incompatible types
nums.add(3.14); // suppose the line above were allowed: a Double is a Number, valid
Integer x = ints.get(2); // but ints and nums are the same list -> boom
List<A> and List<B> have no subtype relationship, no matter how A and B are related. To get one, you need wildcards, the subject of part 2.
Arrays go the other way: Integer[] is a subtype of Number[]. That was a Java 1.0 decision, made before generics, so that methods like Arrays.sort(Object[]) could be written. The price: arrays carry their element type at runtime, so the JVM checks every store and throws ArrayStoreException on a mismatch.
Array T[] |
Generic List<T> |
|
|---|---|---|
| Subtyping | Covariant: Integer[] is a Number[] |
Invariant: List<Integer> unrelated to List<Number> |
| Type info at runtime | Yes (reified) | No (erased) |
| Wrong-type store caught at | Runtime (ArrayStoreException) |
Compile time |
| Primitive elements | Yes (int[]) |
No (List<Integer>) |
Exercises
Exercise 1: A generic transaction
Task (paraphrased): write a generic class with three type parameters for the transaction ID, the amount and the status. The ID is a number or a string, the amount an integer or a floating-point number, the status a string or an enum; create a few objects and print them.
Solution to Exercise 1: a bounded generic record and review notes
Use a record to keep it short, add the bound AMOUNT extends Number so nobody passes a String as the amount, and check for nulls in the compact constructor.
enum TxStatus { PENDING, SUCCESS, FAILED }
record Transaction<ID, AMOUNT extends Number, STATUS>(ID id, AMOUNT amount, STATUS status) {
Transaction {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(amount, "amount");
Objects.requireNonNull(status, "status");
}
}
var t1 = new Transaction<>(1001L, new BigDecimal("250000.50"), TxStatus.SUCCESS);
var t2 = new Transaction<>("TX-ABC", 99, "FAILED");
System.out.println(t1); // Transaction[id=1001, amount=250000.50, status=SUCCESS]
Code-review comment: three type parameters is too many for a real business model. Money should always be BigDecimal (never double) and the status should always be an enum. Generics fit data structures and infrastructure (containers, repositories, caches); business models should use concrete types. The AMOUNT extends Number bound at least blocks the most obvious mistake.
Remember
- Explain how generics move type errors to compile time while the bytecode still has casts.
- Know when a type parameter belongs on the class versus the method, and why a static method must declare its own
<T>. - Write a multiple bound with
&and explain whymaxusesComparable<? super T>. - Explain why
List<Integer>isn’t aList<Number>whileInteger[]is aNumber[]. - Know the
varplus diamond trap and how to avoid it.
Interview questions
Junior
What problem do generics solve?
They move type errors from runtime to compile time.
You can’t put the wrong type into a collection, you don’t need manual casts when reading (the compiler inserts them and guarantees they’re correct), and you can write reusable classes and methods for many types while staying type-safe.
What’s the difference between a generic class and a generic method?
A generic class ties the type to each object; a generic method ties it to each call.
A generic class declares type parameters after the class name (class Box<T>), and all instance methods share that T. A generic method declares them before the return type (static <T> T first(List<T>)), and T is usually inferred from the arguments. Static methods can’t use the class’s type parameters, so they have to be generic methods.
What is the diamond operator, and what’s the trap when you combine it with var?
new ArrayList<>() lets the compiler infer the type argument; with var there’s nothing to infer from, so you get ArrayList<Object>.
The diamond (Java 7) infers from the left-hand side or the context, so you don’t repeat <String>. With var list = new ArrayList<>();, anything you add compiles. With var, put the type argument on the right: var list = new ArrayList<String>();.
Mid
Why isn’t List<Integer> a List<Number> when Integer[] is a Number[]?
Generics are invariant so the compiler can stop you from add(3.14) into a List<Integer>; arrays have been covariant since Java 1.0 and compensate with runtime checks.
Arrays know their element type, so the JVM checks every store and throws ArrayStoreException. Generics are erased, so they can’t be checked at runtime and must be locked down at compile time.
When does a type parameter belong on the class, and when on the method?
On the class when the type is part of the object’s state; on the method when it only matters for one call.
On the class when several methods must agree on it (Cache<K, V>, Repository<T, ID>); each instance is tied to one set of type arguments. On the method especially for static methods, which can’t see the class’s type parameters. Signs it’s in the wrong place: a class declares <T> but only one method uses it, or you have to create a Util<String> just to call a helper.
Why won’t <T> void printArray(T[] arr) accept an int[]? Should an API take arrays or List<T>?
T must be a reference type, so an int[] isn’t a T[] for any T. Business APIs should prefer List<T>.
Autoboxing doesn’t apply to whole arrays, so primitive arrays need their own overload. List<T> is type-safe at compile time, available in immutable form, and free of the covariant ArrayStoreException problem. Arrays fit large numeric data, performance-critical code (an int[] is far more compact than a List<Integer>), and varargs.
Senior
Why does Collections.max have the signature <T extends Object & Comparable<? super T>> T max(Collection<? extends T>)?
Comparable<? super T> accepts types that inherit compareTo from a parent, ? extends T because the collection is a producer, and Object & is a binary-compatibility trick.
For example, LocalDate implements Comparable<ChronoLocalDate>. Erasure uses the first bound, so the erased return type is Object, just like the pre-Java 5 max, instead of Comparable, which keeps code compiled against the old API working.
Useful phrases for interviews
- “Generics move type errors from runtime to compile time; the casts are still there, but the compiler generates them and proves they’re safe.”
- “Java generics are invariant, so a list of integers isn’t a list of numbers. If it were, you could sneak a double into it.”
- “I put the type parameter on the method because it only matters for that one call.”
- “A bound like
T extends Comparable<? super T>lets me call compareTo on T.” - “Arrays are covariant and check writes at runtime; generics are invariant and check at compile time.”
- “With
var, I write the type argument on the right, or the diamond infers Object.” - “The compiler infers T from the arguments, so explicit type witnesses are rare.”
- “A generic class is the right tool for containers and infrastructure; business models usually want concrete types.”
Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.