Generics and type erasure

Mid-level Frequently asked 6 min

On this page

The question

What is type erasure in Java generics?

30-second answer

Generics exist for the compiler. javac checks every use of a type argument, then erases it: a List<String> becomes a plain List whose methods take and return Object, and javac inserts a cast where a value is read. At runtime a List<String> and a List<Integer> share one class, which kept generic code compatible with code written before Java 5.

Understand it

From List<String> to a plain List

Step by step

The source declares List<String> names. The type argument String tells the compiler what the list may hold.

Step 1 of 5
View as text

The drawing shows a pipeline from the .java file to javac, the .class file and the JVM, above three lines of code: List<String> names = new ArrayList<>(), names.add("Ann") and String s = names.get(0).

The source declares List<String> names. The type argument String tells the compiler what the list may hold.

javac checks every call against String: add("Ann") compiles and add(42) is a compile error. The check happens before the program ever runs. The line names.add(42) appears with a mark saying int is a compile error, while add("Ann") is marked as compiling.

Compiling erases the type arguments. The .class file holds a plain List whose add() takes an Object and whose get() returns one. The type arguments <String> and <> are struck out of the first line, and comments show add(Object) and get() returning Object.

Where the value is read as a String, javac inserts a (String) cast after get(0). The bytecode runs it as a checkcast instruction. The last line becomes String s = (String) names.get(0), with the cast highlighted.

At runtime no list object records its type argument: a List<String> and a List<Integer> built as ArrayLists share one class, so their getClass() values are equal. Two boxes, List<String> and List<Integer>, each created with new ArrayList<>(), both point at one box, ArrayList.class, marked as the same class.

The drawing shows a pipeline from the .java file to javac, the .class file and the JVM, above three lines of code: List<String> names = new ArrayList<>(), names.add("Ann") and String s = names.get(0).

The source declares List<String> names. The type argument String tells the compiler what the list may hold.

javac checks every call against String: add("Ann") compiles and add(42) is a compile error. The check happens before the program ever runs. The line names.add(42) appears with a mark saying int is a compile error, while add("Ann") is marked as compiling.

Compiling erases the type arguments. The .class file holds a plain List whose add() takes an Object and whose get() returns one. The type arguments <String> and <> are struck out of the first line, and comments show add(Object) and get() returning Object.

Where the value is read as a String, javac inserts a (String) cast after get(0). The bytecode runs it as a checkcast instruction. The last line becomes String s = (String) names.get(0), with the cast highlighted.

At runtime no list object records its type argument: a List<String> and a List<Integer> built as ArrayLists share one class, so their getClass() values are equal. Two boxes, List<String> and List<Integer>, each created with new ArrayList<>(), both point at one box, ArrayList.class, marked as the same class.

Takeaway: Generics are checked by the compiler, then erased. A cast inserted where a value is read keeps the code type-safe, and at runtime every List shares one class.

Pick the wildcard for each parameter

Build

Give each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
  5. Empty
View as text

Five method parameters each need a list type. The drawing shows each method beside its parameter, with an arrow from the list into the method where it reads and from the method into the list where it writes. Give each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.

The answers are: sum(list) reads Numbers from the list, so it takes List<? extends Number>, a producer. fill(list) adds Integers to the list, so it takes List<? super Integer>, a consumer. In copy(dest, src), the list it reads from is List<? extends T>, the source, and the list it writes to is List<? super T>, the destination. swapFirst(list) reads and writes Integers, so it takes List<Integer> with no wildcard.

Producer extends, consumer super: ? extends where the method reads, ? super where it writes, and no wildcard where it does both.

Five method parameters each need a list type. The drawing shows each method beside its parameter, with an arrow from the list into the method where it reads and from the method into the list where it writes. Give each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.

The answers are: sum(list) reads Numbers from the list, so it takes List<? extends Number>, a producer. fill(list) adds Integers to the list, so it takes List<? super Integer>, a consumer. In copy(dest, src), the list it reads from is List<? extends T>, the source, and the list it writes to is List<? super T>, the destination. swapFirst(list) reads and writes Integers, so it takes List<Integer> with no wildcard.

Producer extends, consumer super: ? extends where the method reads, ? super where it writes, and no wildcard where it does both.

Takeaway: Producer extends, consumer super: a list the method reads from takes ? extends, a list it writes to takes ? super, and a list it does both with takes the exact type.

Producer extends, consumer superA method reads values of type T from a List of ? extends T, the producer, and writes values of type T into a List of ? super T, the consumer. A list the method both reads and writes takes the exact type, List of T.get(): read a Tadd(t): write a Treads and writesList<? extends T>produceryour methodList<? super T>consumerList<T>exact type
Producer extends, consumer superA method reads values of type T from a List of ? extends T, the producer, and writes values of type T into a List of ? super T, the consumer. A list the method both reads and writes takes the exact type, List of T.get(): read a Tadd(t): write a Treads and writesList<? extends T>produceryour methodList<? super T>consumerList<T>exact type
PECS: read from extends, write to super

In code

List<String> names = new ArrayList<>();
names.add("Ann");
// names.add(42);         compile error: int cannot be converted to String
String s = names.get(0);  // javac inserts a (String) cast here

 Wrong List raw = names;         // raw type: the compiler stops checking
raw.add(42);              // unchecked warning, but it runs
String t = names.get(1);  // ClassCastException at the inserted cast

List<Integer> ids = new ArrayList<>();
System.out.println(names.getClass() == ids.getClass());   // true
Checked at compile time, erased at runtime
static double sum(List<? extends Number> list) {      // reads Numbers
    double total = 0;
    for (Number n : list) total += n.doubleValue();
    return total;
}

static void fill(List<? super Integer> list) {        // writes Integers
    for (int i = 1; i <= 3; i++) list.add(i);
}

static <T> void copy(List<? super T> dest, List<? extends T> src) {
    for (T item : src) dest.add(item);
}

List<Number> numbers = new ArrayList<>();
fill(numbers);                    // [1, 2, 3]
copy(numbers, List.of(2.5));      // [1, 2, 3, 2.5]
System.out.println(sum(numbers)); // 8.5
Producer extends, consumer super
Two generic lists, one runtime classnames, a List of String, and ids, a List of Integer, are both created with new ArrayList. After erasure, getClass on each returns the same class, java.util.ArrayList, so comparing the two classes with == gives true.getClass()getClass()names: List<String>java.util.ArrayListids: List<Integer>names.getClass() ==ids.getClass(): true
Two generic lists, one runtime classnames, a List of String, and ids, a List of Integer, are both created with new ArrayList. After erasure, getClass on each returns the same class, java.util.ArrayList, so comparing the two classes with == gives true.getClass()getClass()names: List<String>java.util.ArrayListids: List<Integer>names.getClass() ==ids.getClass(): true
List<String> and List<Integer> erase to one ArrayList class
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;
}

Integer top = max(List.of(3, 9, 4));     // 9
String last = max(List.of("b", "a"));    // "b"
A bounded generic method works for any Comparable type

Solve it

Why can’t you write new T[16], and how does a generic container store its items?

A candidate writes a generic Box<T> backed by T[] items = new T[16] and gets “generic array creation”. Explain the error and give two ways to build the container.

  1. Recall erasure. At runtime T is gone and becomes Object, so the JVM (Java Virtual Machine) does not know which element type to create.
  2. Recall that arrays are reified. An array checks every store against its element type at runtime, so it must be created with a real class. Erasure leaves none.
  3. Option one: ask the caller. Take an IntFunction<T[]> such as String[]::new, as Collection.toArray does. The array is a real String[].
  4. Option two: hide an Object[]. Store Object[] and cast on the way out, as ArrayList does. Never return the array itself.
  5. Check. Both compile without raw types; the unchecked cast stays private, with one @SuppressWarnings on it.
class Box<T> {
    private final T[] items;
    Box(IntFunction<T[]> newArray, int size) { items = newArray.apply(size); }   // a real T[] from the caller
    void set(int i, T item) { items[i] = item; }
    T get(int i) { return items[i]; }
}
Box<String> names = new Box<>(String[]::new, 16);

class Stack<T> {
    private Object[] items = new Object[16];       // what ArrayList does internally
    private int size;
    void push(T item) { items[size++] = item; }
    @SuppressWarnings("unchecked") T pop() { return (T) items[--size]; }   // safe: only T goes in
}
Two ways to back a generic container

How to answer

  • The compiler rejects names.add(42) on a List<String>, so the type check happens before the program runs.
  • Erasure replaces a type parameter with its bound: T becomes Object, and T extends Number becomes Number.
  • javac inserts a checkcast where a generic value is read, as in String s = names.get(0).
  • new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass() is true.
  • Erasure is why new T(), new T[n] and o instanceof List<String> on an Object do not compile.

Common mistakes

  • Saying the JVM checks the type argument on every add; at runtime only the inserted casts check anything.
  • Saying every trace of the type argument is gone; field and method signatures keep it for reflection, objects do not.

Follow-up questions

What is the difference between ? extends and ? super, and what does PECS mean?

PECS stands for producer extends, consumer super. A List<? extends Number> produces values: every element reads as a Number, but you cannot add one, because the list might be a List<Double>. A List<? super Integer> consumes values: you can add Integers, but reading gives only Object. A list the method both reads and writes takes the exact type, with no wildcard.

  • List<? extends Number> l; l.add(1) is a compile error; null is the only value you can add.
  • Reading a List<? super Integer> gives Object: Integer x = l.get(0) does not compile.
  • Collections.copy(List<? super T> dest, List<? extends T> src) follows the rule: it reads the source and writes the destination.
  • Wildcards widen an API: sum(List<? extends Number>) accepts a List<Integer> and a List<Double>.

See it in the infographic: Pick the wildcard for each parameter

Why can't you write new T() inside a generic class or method?

Because T is erased. The bytecode does not record which class T stands for, so the compiler cannot emit a constructor call, and new T() fails with "unexpected type". For the same reason new T[n] is a "generic array creation" error. Pass the knowledge in instead: a Supplier<T> such as StringBuilder::new, or a Class<T> whose constructor you call through reflection.

  • A Supplier<T> is the type-safe fix, and make(StringBuilder::new) returns a StringBuilder.
  • A Class<T> token also works: type.getDeclaredConstructor().newInstance(), at the cost of checked reflection exceptions.
  • For arrays, use a List<T> or take an IntFunction<T[]>, as Collection.toArray(String[]::new) does.
static <T> T make(Supplier<T> factory) {
    return factory.get();
}

StringBuilder sb = make(StringBuilder::new);

See it in the infographic: From List<String> to a plain List

What is a raw type, and why should you avoid it?

A raw type is a generic type used without type arguments, such as List instead of List<String>. It exists so code written before generics still compiles. The compiler stops checking it and gives only an unchecked warning, so a raw List can put an Integer into a List<String>. The error surfaces later, as a ClassCastException at the cast inserted where the value is read.

  • By default javac prints only a summary note; -Xlint:rawtypes and -Xlint:unchecked warn on each line.
  • The failure is far from the bug, because the add succeeds and a later get throws.
  • Use List<?> for a list of unknown type, which you can read as Object but cannot add to except null.
List<String> names = new ArrayList<>();
List raw = names;          // raw type
raw.add(42);               // unchecked warning, runs
String s = names.get(0);   // ClassCastException

See it in the infographic: From List<String> to a plain List

Why is a List<Integer> not a List<Number>?

If it were, code holding it as a List<Number> could add a Double, and the List<Integer> would then hold a Double. So generics are invariant and the assignment is a compile error. Arrays are covariant instead: Object[] arr = new Integer[1] compiles, and storing a String in it throws ArrayStoreException. Accept both with List<? extends Number>.

What is a bridge method?

A synthetic method javac adds so that overriding still works after erasure. When Box implements Comparable<Box>, its compareTo(Box) does not match the erased compareTo(Object), so javac generates a compareTo(Object) that casts its argument to Box and calls compareTo(Box). Reflection reports it with isBridge() returning true.

Check yourself

1. What does this print?
List<String> names = new ArrayList<>();
List<Integer> ids = new ArrayList<>();
System.out.println(names.getClass() == ids.getClass());
Show answers
  • true: Correct. Erasure leaves one ArrayList class, whatever the type argument.
  • false: Incorrect. Type arguments exist only for the compiler, so both lists share a class.
  • It does not compile: Incorrect. Comparing two Class objects with == compiles.
2. A method only reads Numbers from its list parameter and must accept both a List<Integer> and a List<Double>. Which parameter type fits?
Show answers
  • List<? extends Number>: Correct. The list is a producer, every element reads as a Number, and both lists qualify.
  • List<? super Number>: Incorrect. That accepts a List<Number> or a List<Object>, not a List<Integer>.
  • List<Number>: Incorrect. Generics are invariant, so a List<Integer> is not a List<Number>.