Explain it simply
Generics in plain language
Generics let you write a class or method for "some type T" instead of locking it to one type. List<String> means "a list that only accepts Strings" and List<Integer> means the same for Integers: one piece of code, many typed versions. The compiler catches a wrong type before the program ever runs.
Think of labelled jars in a restaurant kitchen. Put sugar into a jar labelled "salt" and nobody notices until the food is cooked. A generic jar refuses anything that does not match its label at the door, and when you take something out you know exactly what you are getting.
Problem → Why → Solution
The problem: raw types and casts
Before Java 5, collections had no type parameters: an ArrayList stored Object, and every read needed a cast. That style, the raw type, still compiles today, so people copying old tutorials still write it. The code below compiles, yet a number slipped in somewhere goes unnoticed until the final cast explodes with ClassCastException.
List names = new ArrayList(); // raw type: holds Object
names.add("Ada");
names.add(42); // nothing stops this
String second = (String) names.get(1); // ClassCastException at runtimeMove the type error to compile time
A raw list keeps no record of what type it holds, so the compiler cannot help, and the error surfaces where the crash happens (the cast) instead of where the mistake was made (the add). Write List<String> and names.add(42) becomes a compile error, while get() returns a String directly with no cast.
Core concept: type parameters, bounds, wildcards and erasure
A type parameter is declared in angle brackets: after the class name for a generic class (class Box<T>), and before the return type for a generic method (static <T> T first(List<T> values)). At a call, the compiler infers T from the arguments: in first(List.of("Ada")), T is String, so the result goes into a String variable with no cast. When creating objects, the diamond in new ArrayList<>() infers the type from the left-hand side. By convention, type parameters are single capital letters: T for a type, E for an element, K and V for a map's keys and values.
An unbounded T could be anything, so only Object's methods are available on it. Add a bound such as <T extends Comparable<T>> and the compiler knows every T has compareTo(), so you can write a max method, and calling it with a non-comparable type is a compile error. In a bound, extends is used for classes and interfaces alike.
Generic types are invariant: Integer is a subtype of Number, but List<Integer> is not a subtype of List<Number>. If it were, a List<Number> reference could put a Double into a list of Integers. When you need flexibility, use wildcards: List<? extends Number> accepts any list of Number subtypes for reading (a producer), and List<? super Integer> accepts lists you can add Integers to (a consumer). Remember it as PECS: Producer Extends, Consumer Super.
Why List<Integer> cannot be a List<Number>
------------------------------------------
List<Integer> ints = new ArrayList<>();
List<Number> nums = ints; // compile error -- but suppose it worked:
nums.add(3.14); // a Double is now inside ints
Integer i = ints.get(0); // ClassCastException
List<? extends Number> readOnly = ints; // OK: read Numbers, add nothing
List<? super Integer> sink = nums; // OK: add IntegersJava implements generics with type erasure: after checking the types, the compiler removes the type arguments, so at runtime List<String> and List<Integer> are the same List class. That is why you cannot write new T() or new T[10], and why primitive types cannot be type arguments; use List<Integer> instead of List<int>, and autoboxing converts between int and Integer.
- <T> is a blank for a type
- Each call site fills T (inference)
- Compiler checks every add and get
- At runtime T is erased
Using a raw type breaks the promise yourself: the compiler only warns and hands the runtime crash back to you.
General pattern
class Container<T> { T get() { ... } } // generic class
static <T> T pick(List<T> items) { ... } // generic method
static <T extends Comparable<T>> T best(List<T> xs) // bounded
static double total(List<? extends Number> source) // producer: read
static void fill(List<? super Integer> target) // consumer: write
Container<String> c = new Container<>(); // diamond inferenceDeclare the type parameter after the class name or before a method's return type, add an extends bound when you need T's methods, and choose ? extends or ? super depending on whether a parameter is only read from or written to.
Worked example: a first() that keeps the type
first() accepts a list of any element type and returns an element of that same type. main calls it with a String list, so T is String and the result goes into String name without a cast. A check rejects empty lists.
import java.util.List;
class Main {
static <T> T first(List<T> values) {
if (values.isEmpty()) throw new IllegalArgumentException("empty list");
return values.getFirst();
}
public static void main(String[] args) {
String name = first(List.of("Ada", "Linus"));
System.out.println(name);
}
}Code breakdown
- Declare T
static <T> T first(List<T> values) {The <T> before the return type declares a generic method. The parameter is a List of T and the return type is T, so input and output are linked.
- Guard the empty case
if (values.isEmpty()) throw new IllegalArgumentException("empty list");An empty list has no first element, so the method fails early with a clear message.
- Typed return
return values.getFirst();getFirst() is a Java 21 SequencedCollection method that returns a T. On versions before Java 21, use values.get(0).
- Inference at the call site
String name = first(List.of("Ada", "Linus"));The compiler sees List<String> and infers T = String. No (String) cast is needed, and assigning the result to an Integer variable would be a compile error.
AdaA generic class and a bounded type parameter
Box<T> is a generic class holding one value. max() bounds T with Comparable<T>, so it may call compareTo(). Integer and String are both Comparable, so max() works with either.
import java.util.List;
public class Boxes {
public static void main(String[] args) {
Box<String> label = new Box<>("fragile");
String text = label.get(); // no cast needed
System.out.println(text.toUpperCase());
System.out.println(max(List.of(3, 9, 4)));
System.out.println(max(List.of("pear", "apple", "fig")));
}
static <T extends Comparable<T>> T max(List<T> values) {
T best = values.getFirst();
for (T value : values) {
if (value.compareTo(best) > 0) {
best = value;
}
}
return best;
}
}
class Box<T> {
private final T value;
Box(T value) {
this.value = value;
}
T get() {
return value;
}
}The output is FRAGILE, then 9, then pear (strings compare alphabetically, so "pear" is the largest).
Wildcards: ? extends and ? super
sum() only reads numbers from its list, so it uses ? extends Number and accepts both List<Integer> and List<Double>. addDefaults() only adds Integers, so it uses ? super Integer and accepts both List<Number> and List<Object>. Written with a plain List<Number>, each method would accept only that exact type.
import java.util.ArrayList;
import java.util.List;
public class Wildcards {
public static void main(String[] args) {
System.out.println(sum(List.of(1, 2, 3))); // List<Integer>
System.out.println(sum(List.of(0.5, 1.5))); // List<Double>
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
addDefaults(numbers);
addDefaults(objects);
System.out.println(numbers + " " + objects);
}
static double sum(List<? extends Number> source) { // producer: read only
double total = 0;
for (Number n : source) {
total += n.doubleValue();
}
return total;
}
static void addDefaults(List<? super Integer> target) { // consumer: write
target.add(1);
target.add(2);
}
}This program prints 6.0, then 2.0, then [1, 2] [1, 2]. Try source.add(4) inside sum() and it will not compile: a ? extends Number list might really be a List<Double>, so the compiler lets you add nothing except null.
In real projects
Generics in real projects
You use generics every day long before you write a generic class. List<Order>, Map<String, Customer> and Optional<User> all declare what they carry, so your IDE can autocomplete and the compiler catches mismatches. The JDK's own Collections.copy(List<? super T> dest, List<? extends T> src) signature is PECS in action.
- API response wrappers: one ApiResponse<T> gives every endpoint, such as ApiResponse<User> or ApiResponse<List<Order>>, the same envelope without losing the payload type.
- Repository bases: a Repository<T, ID> interface offers save(T) and findById(ID) with one signature for every entity; Spring Data's CrudRepository<T, ID> follows this shape.
- Utility methods: helpers such as groupBy, partition or retry<T>(Supplier<T>) are written once with type parameters and reused across the codebase with no casts.
Common mistakes
Common mistakes with generics
Using raw types and ignoring the warning
List list = new ArrayList(); compiles, but the compiler issues an "unchecked" warning. That warning is telling you type safety is gone: put a wrong object in, and a ClassCastException fires later somewhere else. Always write the type argument, or use List<?> when the type is truly unknown.
Passing a List<Integer> as a List<Number>
Calling static double sum(List<Number> xs) with a List<Integer> fails with "incompatible types: List<Integer> cannot be converted to List<Number>". Rather than forcing it with casts, change the parameter to List<? extends Number>, which is the right answer for a method that only reads.
Fighting erasure
new T[10] fails with "generic array creation", and checking an Object with instanceof List<String> fails with "Object cannot be safely cast to List<String>", because the String part no longer exists at runtime. Use a List<T> instead of an array, and pass a Supplier<T> or Class<T> when you need to create new instances.
Overloading on the type argument alone
Declaring both void process(List<String> x) and void process(List<Integer> x) fails with "name clash: ... have the same erasure", since after erasure both become process(List). Give them different names, such as processNames() and processIds().
Mini challenge
Mini challenge: Pair, copyInto and minOf
Write three generic pieces: a generic record Pair<A, B> that holds two values and can flip them with swap(); copyInto(), which copies elements from a source list into a target list; and minOf(), which finds the smallest element for any Comparable type.
- Pair<A, B>.swap() returns a Pair<B, A>
- copyInto() takes a List<? super T> target and a List<? extends T> source (PECS)
- minOf() uses the bound <T extends Comparable<T>> and rejects an empty list with IllegalArgumentException
- Show copyInto() copying both an Integer list and a Double list into one List<Number>
import java.util.ArrayList;
import java.util.List;
public class GenericKit {
public static void main(String[] args) {
// TODO: build a Pair<String, Integer> ("Ada", 36), print it and its swap()
// TODO: copy List.of(1, 2) and List.of(2.5) into one List<Number>, print it
// TODO: print minOf for List.of(7, 3, 9) and List.of("pear", "apple", "fig")
}
// TODO: static <T> void copyInto(List<? super T> target, List<? extends T> source)
// TODO: static <T extends Comparable<T>> T minOf(List<T> values)
}
// TODO: record Pair<A, B>(A first, B second) with a swap() methodExpected: Five lines: Pair[first=Ada, second=36], Pair[first=36, second=Ada], [1, 2, 2.5], 3 and apple.
Show hint
Records can be generic: record Pair<A, B>(A first, B second) { ... }. Inside swap(), new Pair<>(second, first) lets the diamond infer Pair<B, A>. In copyInto(), the source produces Ts and the target accepts Ts, so one for loop is enough.
Show solution
import java.util.ArrayList;
import java.util.List;
public class GenericKit {
public static void main(String[] args) {
Pair<String, Integer> person = new Pair<>("Ada", 36);
Pair<Integer, String> flipped = person.swap();
System.out.println(person);
System.out.println(flipped);
List<Number> numbers = new ArrayList<>();
copyInto(numbers, List.of(1, 2)); // T = Integer
copyInto(numbers, List.of(2.5)); // T = Double
System.out.println(numbers);
System.out.println(minOf(List.of(7, 3, 9)));
System.out.println(minOf(List.of("pear", "apple", "fig")));
}
static <T> void copyInto(List<? super T> target, List<? extends T> source) {
for (T item : source) {
target.add(item);
}
}
static <T extends Comparable<T>> T minOf(List<T> values) {
if (values.isEmpty()) {
throw new IllegalArgumentException("minOf needs at least one value");
}
T smallest = values.get(0);
for (T value : values) {
if (value.compareTo(smallest) < 0) {
smallest = value;
}
}
return smallest;
}
}
record Pair<A, B>(A first, B second) {
Pair<B, A> swap() {
return new Pair<>(second, first);
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A type parameter (<T>) makes classes and methods type-safe for many types without casts, and the compiler usually infers T.
- <T extends Bound> lets you call T's methods and rejects unsuitable types at compile time.
- Generic types are invariant; use ? extends to read and ? super to write (PECS).
- Because of type erasure there is no new T(), no generic array creation and no List<int>; never use raw types.