Lesson 10 of 12 · 9 min · Collections, streams and generics
Generics: type-safe code with type parameters
What you will learn
- What generics are and what problem they solve
- Write generic classes, interfaces and methods
- Bounded type parameters (
extends) - Wildcards (
?,? extends,? super) and the PECS rule - Type erasure and the restrictions it causes
In simple words
Before generics, a Java list could hold anything, so you could put a number in a list of names and only find out when the program crashed. Generics let you label the container: List<String> means "only strings go in here", and the compiler checks it before you run. A type parameter such as T is a blank you fill in later, like a lunch box that is made once and can carry rice or fruit, but each time you pick one.
Words to know
- Generic type: a class or interface with a type parameter, such as
List<T>. - Type parameter: a placeholder for a type, written like
T,E,KorV. - Wildcard: a
?that stands for an unknown type. - Type erasure: the compiler removing generic type information after checking it.
The problem generics solve
List names = new ArrayList(); // raw type: pre-Java 5 style
names.add("Asha");
names.add(42); // compiles!
String first = (String) names.get(1); // ClassCastException at run time
With generics the error appears at compile time:
List<String> names = new ArrayList<>();
names.add("Asha");
names.add(42); // compile error: int cannot be added to List<String>
String first = names.get(0); // no cast needed
The <> (diamond) lets the compiler infer the type on the right. Generics only work with reference types: use List<Integer>, not List<int>. Primitives are boxed automatically (int to Integer), which costs memory and speed; for large numeric data use arrays or primitive streams.
A generic class
public 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; }
}
Box<String> a = new Box<>("hello");
String s = a.get();
Box<Integer> b = new Box<>(7);
A type parameter can appear in fields, method parameters and return types. Conventional names: T (type), E (element), K (key), V (value), R (result). A class can have several: Pair<K, V>. Generic interfaces work the same way: Comparable<T>, Function<T, R>, Repository<T, ID>.
public record Pair<A, B>(A first, B second) {}
Pair<String, Integer> p = new Pair<>("pen", 40);
Generic methods
A method can declare its own type parameter before the return type:
public static <T> T firstOrDefault(List<T> list, T fallback) {
return list.isEmpty() ? fallback : list.get(0);
}
String s = firstOrDefault(List.of("a", "b"), "none"); // T inferred as String
int n = firstOrDefault(List.of(), 0); // T inferred as Integer
Use generic methods when the type relationship is between the method's parameters and return value, without making the whole class generic. The compiler infers T from the arguments, so you rarely write it explicitly.
Bounded type parameters
Restrict what T can be with extends (for both classes and interfaces):
public static <T extends Comparable<T>> T max(List<T> list) {
T best = list.get(0);
for (T item : list) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
max(List.of(3, 9, 4)); // 9
max(List.of("pen", "bag")); // "pen"
Without the bound, T is just Object, and compareTo would not exist. Multiple bounds use &: <T extends Number & Comparable<T>> (a class first, then interfaces).
Wildcards and PECS
Generics are invariant: a List<Integer> is not a List<Number>, even though Integer extends Number. If it were, you could add a Double to a list that is really a list of Integer. Wildcards express flexible relationships:
| Wildcard | Means | You can |
|---|---|---|
List<?> |
a list of unknown type | read items as Object; add nothing but null |
List<? extends Number> |
a list of Number or any subclass (upper bound) | read items as Number; cannot add |
List<? super Integer> |
a list of Integer or any superclass (lower bound) | add Integers; reads give Object |
The rule PECS: Producer Extends, Consumer Super. If the collection produces values you read, use ? extends; if it consumes values you put in, use ? super.
// source produces numbers, destination consumes them
public static void copy(List<? extends Number> src, List<? super Number> dest) {
for (Number n : src) dest.add(n);
}
double sum(List<? extends Number> numbers) { // works for List<Integer>, List<Double>, ...
double total = 0;
for (Number n : numbers) total += n.doubleValue();
return total;
}
Collections.copy(dest, src), Comparator<? super T> and Stream.map(Function<? super T, ? extends R>) all follow PECS, which is why they accept subtypes and supertypes sensibly.
Type erasure
Generics are a compile-time feature. After checking, the compiler erases type parameters: List<String> and List<Integer> both become plain List in the bytecode, with casts inserted where needed. This kept compatibility with old code, but it brings restrictions:
- You cannot create
new T()ornew T[10]. - You cannot use
instanceof List<String>(onlyinstanceof List<?>); there is noT.class. List<String>andList<Integer>have the same runtime class (list1.getClass() == list2.getClass()is true).- You cannot overload methods that differ only by generic type (
void f(List<String>)andvoid f(List<Integer>)clash). - Static members cannot use the class's type parameter.
- Primitive types are not allowed as arguments.
If you need the type at run time, pass a Class<T> token (Class<T> type) or a supplier (Supplier<T>), as frameworks do.
Raw types and unchecked warnings
Using a generic class without a type argument (List list) is a raw type. It turns off checks, and you get unchecked warnings. Avoid raw types in new code. When you must cast (for example in older libraries), confine @SuppressWarnings("unchecked") to the smallest scope and explain why with a comment.
Generic design tips
- Prefer generic methods over a generic class when only a method needs the parameter.
- Prefer wildcards in parameters (
List<? extends Shape>) for flexibility, and concrete types in return values so callers do not need wildcards. - Prefer lists over arrays with generics (arrays are covariant and reified, which clashes with erasure).
- Keep type parameter names meaningful when there are several (
<K, V>,<Req, Res>). - Do not use a wildcard as a return type.
Common mistakes
- Assuming
List<Integer>is aList<Number>. - Using raw types and ignoring warnings.
- Trying to add to a
List<? extends T>. - Using
T[]creation orinstanceofwith generics. - Too much generic cleverness where a simple concrete type would be clearer.
Try it yourself
- Write
Pair<A, B>and a generic methodswapreturningPair<B, A>. - Write
<T extends Comparable<T>> T max(List<T>)and test it with integers and strings. - Write
sum(List<? extends Number>)and call it withList<Integer>andList<Double>. - Try adding an integer to a
List<? extends Number>and read the error. - Create a raw
List, add the wrong type, and see the run-time failure.
Check yourself
What does List<String> give you over a raw List?
Compile-time checking that only strings go in and no casts when reading, so type errors are found before running.
Why is List<Integer> not a subtype of List<Number>?
If it were, you could add a Double through the List<Number> view and corrupt the list of integers; generics are invariant.
What does PECS stand for?
Producer extends, consumer super: use ? extends T when you read from a structure and ? super T when you write to it.
What is type erasure?
The compiler removes generic type arguments after type checking, so at run time List<String> and List<Integer> are the same class.
Interview questions
What are generics and why were they introduced?
A way to parameterise classes, interfaces and methods by type, giving compile-time type safety and removing casts. They were introduced in Java 5 so collections could check their element types.
Explain bounded type parameters and wildcards.
A bounded type parameter (<T extends Comparable<T>>) restricts what T can be and lets you call the bound's methods. Wildcards (?, ? extends X, ? super X) express unknown or flexible types in parameters, following PECS.
Why can't you create a generic array like new T[10]?
Arrays keep their element type at run time, but generics are erased, so the JVM could not enforce type safety; use List<T> or a Class token with Array.newInstance.
Summary
- Generics make collections and APIs type-safe at compile time and remove casts.
- Write generic classes, interfaces and methods with type parameters; bound them with
extends. - Wildcards add flexibility; remember PECS; generics are invariant.
- Erasure removes type arguments at run time, causing restrictions on arrays,
instanceofandnew T().
Going deeper
- dev.java: Generics: the official guide to generics.
- The Java Tutorials: Generics: bounded types, wildcards and erasure.
- Java Language Specification: Types, values and variables: formal rules for parameterised types.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.