Generics, Type Erasure and Wildcards
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Generics questions are where interviewers separate memorised answers from real understanding: type erasure, wildcards and "why is List<Integer> not a List<Number>?". They want the reason behind each rule, not only the rule.
Why generics: type safety and no casts
A type parameter is a placeholder such as T in List<T> or Box<T>. It is filled with a real type when the class is used, so the Java compiler (javac) can check what goes in and add no casts when it comes out.
Generics are the base of every collections answer. The program reads a mark from a raw list and from a generic list, and shows when each one fails.
Example 1 · A raw list fails at runtime; a generic list fails at compile time
import java.util.ArrayList;import java.util.List;
public class RawVsGenericDemo { @SuppressWarnings({"rawtypes", "unchecked"}) static void rawVersion() { List marks = new ArrayList(); marks.add(85); marks.add("ninety"); // compiles: nothing stops it try { for (Object o : marks) { Integer m = (Integer) o; // cast needed on every read System.out.println("Raw read: " + m); } } catch (ClassCastException e) { System.out.println("Raw list failed at runtime: ClassCastException"); } }
public static void main(String[] args) { rawVersion();
List<Integer> marks = new ArrayList<>(); marks.add(85); // marks.add("ninety"); // compile error: String cannot be converted to Integer int first = marks.get(0); System.out.println("Generic read: " + first); }}Raw read: 85 Raw list failed at runtime: ClassCastException Generic read: 85
What this code does
- The raw list accepts a
String, and the mistake shows up only when the cast runs on the second element. - With
List<Integer>, adding aStringis rejected by the compiler, andgetneeds no cast.
A generic type such as List<String> tells the compiler what the list holds. Adding an Integer is a compile error, and get returns a String with no cast. Before Java 5, lists were raw types that held Object: you cast on every read, and a wrong element failed only at runtime with ClassCastException. Revise: Why generics (opens in a new tab).
So generics move type errors from runtime to compile time.
- Compile-time type checks instead of runtime
ClassCastException. - No casts when reading:
String s = names.get(0);. - Reusable code: one
Box<T>for every type. - Raw types (
List list) still compile, with warnings, only for old code.
Type erasure: what remains at runtime
Type erasure means the Java compiler checks generic types and then removes them from the bytecode. A T becomes Object (or its bound), and the compiler adds casts where values come out.
Erasure explains most generics trick questions. The program shows that two list types share one class at runtime, then shows the usual workarounds.
Example 2 · Erasure at runtime, and the workarounds
import java.lang.reflect.Array;import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;
class Factory<T> { private final Supplier<T> maker;
Factory(Supplier<T> maker) { this.maker = maker; // instead of new T() }
T make() { return maker.get(); }}
public class ErasureDemo { @SuppressWarnings("unchecked") static <T> T[] newArray(Class<T> type, int size) { return (T[]) Array.newInstance(type, size); // instead of new T[size] }
public static void main(String[] args) { List<String> names = new ArrayList<>(); List<Integer> marks = new ArrayList<>(); System.out.println("Same class at runtime? " + (names.getClass() == marks.getClass())); System.out.println("Class name: " + names.getClass().getName());
Object o = names; System.out.println("o instanceof List<?>: " + (o instanceof List<?>));
Factory<StringBuilder> f = new Factory<>(StringBuilder::new); System.out.println("Made: " + f.make().append("roll-21"));
String[] seats = newArray(String.class, 3); System.out.println("Array type: " + seats.getClass().getSimpleName() + ", length " + seats.length); }}Same class at runtime? true Class name: java.util.ArrayList o instanceof List<?>: true Made: roll-21 Array type: String[], length 3
What this code does
- Both lists are plain
ArrayListobjects at runtime: the<String>and<Integer>were erased after compiling. - A
Supplier<T>replacesnew T(), and aClass<T>token letsArray.newInstancebuild a realString[].
In the bytecode, List<String> and List<Integer> are both just List, a T becomes Object (or its bound, such as Number for T extends Number), and the compiler inserts casts where values come out. Java chose this so new generic code could run with old, pre-generic libraries. Revise: Type erasure and limits (opens in a new tab).
Because the type is gone at runtime, several things are illegal. These are the real javac messages:
new T()→ "unexpected type, required: class, found: type parameter T". Pass aSupplier<T>orClass<T>instead.new T[3]→ "generic array creation". UseList<T>orArray.newInstance(type, n).List<int>→ "unexpected type, required: reference, found: int". UseList<Integer>.print(List<String>)andprint(List<Integer>)together → "name clash: ... have the same erasure".
Fix the error
Fix the erasure errors
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
A generic class must create objects of its type.
Error
Maker.java:9: error: unexpected type
return new T();
^
required: classo instanceof List<String> is also rejected ("Object cannot be safely cast to List<String>"); o instanceof List<?> is allowed.Wildcards: ? extends vs ? super and PECS
A wildcard ? means "some unknown type". ? extends T accepts T or a subtype and is for reading; ? super T accepts T or a supertype and is for writing.
Wildcards decide what a method may read or write. The program sums fees from three kinds of list and copies values into a List<Number> and a List<Object>.
Example 3 · PECS: read with extends, write with super
import java.util.ArrayList;import java.util.List;
public class PecsDemo { // Producer: we only READ numbers from it static double total(List<? extends Number> amounts) { double sum = 0; for (Number n : amounts) { sum += n.doubleValue(); } return sum; }
// Consumer: we only WRITE integers into it static void addRollNumbers(List<? super Integer> target, int from, int to) { for (int r = from; r <= to; r++) { target.add(r); } }
public static void main(String[] args) { List<Integer> fees = List.of(1200, 800, 500); List<Double> fines = List.of(12.5, 7.5); System.out.println("Fees total: " + total(fees)); System.out.println("Fines total: " + total(fines));
List<Number> numbers = new ArrayList<>(); List<Object> objects = new ArrayList<>(); addRollNumbers(numbers, 1, 3); addRollNumbers(objects, 7, 8); System.out.println("Into List<Number>: " + numbers); System.out.println("Into List<Object>: " + objects); }}Fees total: 2500.0 Fines total: 20.0 Into List<Number>: [1, 2, 3] Into List<Object>: [7, 8]
What this code does
totalreads from its list, so? extends Numberlets it accept bothList<Integer>andList<Double>.addRollNumberswritesIntegers, so? super Integerlets it fill aList<Number>or aList<Object>. Callingamounts.add(5)insidetotalwould not compile.
List<? extends Number> accepts a list of Number or any subtype, such as List<Integer> or List<Double>. You can read Numbers from it, but you cannot add (except null), because the real element type is unknown.
List<? super Integer> accepts a list of Integer or any supertype, such as List<Number> or List<Object>. You can add Integers to it, but reading gives only Object. PECS sums it up: Producer Extends, Consumer Super. A parameter you read from produces values, so use extends; one you write into consumes values, so use super. Collections.copy(List<? super T> dest, List<? extends T> src) is the textbook case. Revise: Wildcards (opens in a new tab).
Predict the output
Predict the wildcard code
Pick what each snippet does.
Round 1 of 3
Adding to a producer list.
Why List<Integer> is not a List<Number>
Generics are invariant: List<Integer> is not a List<Number>, even though Integer is a Number. Invariant means the type arguments must match exactly.
Compare arrays and generic lists. The program shows an array failing at runtime, then reads a List<Integer> safely through ? extends Number.
Example 4 · Invariant lists vs covariant arrays
import java.util.ArrayList;import java.util.List;
public class InvarianceDemo { public static void main(String[] args) { Object[] seats = new String[2]; // arrays are covariant: compiles seats[0] = "A1"; try { seats[1] = 42; } catch (ArrayStoreException e) { System.out.println("Array: ArrayStoreException at runtime"); }
List<Integer> marks = new ArrayList<>(List.of(70, 80)); // List<Number> numbers = marks; // compile error: List<Integer> cannot be converted to List<Number> List<? extends Number> readOnly = marks; Number first = readOnly.get(0); System.out.println("Read through ? extends: " + first); // readOnly.add(90); // compile error: int cannot be converted to CAP#1 System.out.println("Marks unchanged: " + marks); }}Array: ArrayStoreException at runtime Read through ? extends: 70 Marks unchanged: [70, 80]
What this code does
- Arrays check element types at runtime, so the bad store compiles and then throws
ArrayStoreException. - Lists are checked at compile time instead:
List<Number> numbers = marksis rejected, whileList<? extends Number>allows reading but not adding.
Assigning a List<Integer> to a List<Number> gives "incompatible types: List<Integer> cannot be converted to List<Number>".
The reason is safety. If it were allowed, code holding the list as List<Number> could add a Double, and the original List<Integer> would then contain a Double. Arrays are covariant (Integer[] is an Object[]), which is why the same mistake with arrays compiles and fails at runtime with ArrayStoreException. Use List<? extends Number> when you only need to read.
Writing a generic method with a bounded type
A bounded type parameter limits what T can be, such as <T extends Number>. Inside the method, T can use the bound's methods, and after erasure T becomes the bound.
Writing a generic method is the standard coding question. The program has max for any comparable type, average for numbers and a method that swaps a pair.
Example 5 · Bounded generic methods: max, average and a pair
import java.util.List;
record Pair<A, B>(A first, B second) {}
public class BoundedMethodDemo { static <T extends Comparable<? super T>> T max(List<? extends T> items) { T best = items.get(0); for (T item : items) { if (item.compareTo(best) > 0) { best = item; } } return best; }
static <T extends Number> double average(List<T> values) { double sum = 0; for (T v : values) { sum += v.doubleValue(); // allowed because T extends Number } return sum / values.size(); }
static <A, B> Pair<B, A> swap(Pair<A, B> p) { return new Pair<>(p.second(), p.first()); }
public static void main(String[] args) { System.out.println("Top mark: " + max(List.of(72, 95, 88))); System.out.println("Last name: " + max(List.of("Asha", "Ravi", "Kiran"))); System.out.println("Average CGPA: " + average(List.of(8.5, 7.9, 9.1))); System.out.println("Swapped: " + swap(new Pair<>("Ravi", 21))); }}Top mark: 95 Last name: Ravi Average CGPA: 8.5 Swapped: Pair[first=21, second=Ravi]
What this code does
<T extends Comparable<? super T>>letsmaxcallcompareToon any comparable type; the compiler infers T asIntegerand thenString.<T extends Number>makesdoubleValue()available, and the generic recordPair<A, B>shows a method with two type parameters.
A generic method declares its own type parameter before the return type: static <T> void swap(T[] a, int i, int j).
The classic interview answer is a max method that works for any comparable type. Usually the compiler infers T from the arguments, so you call it like a normal method. Revise: Bounded types (opens in a new tab) and Generic methods (opens in a new tab).
Find the bug
Find the generics bug
Each snippet will not compile. Tap the wrong line, then check the fix.
A max for any comparable type.
Round 1 of 3Next step
Check your understanding
12 quick questions