Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 201 ยท Generics and Functional Programming

Type Erasure and Generic Limitations

Learn how Java type erasure works, why new T(), generic arrays, primitives and instanceof List<String> aren't allowed, the workarounds, heap pollution and @SafeVarargs.

Generics in Java are a compile-time feature. The compiler uses type arguments like <String> to check your code and insert casts, and then it removes them. In the compiled bytecode, a List<String> and a List<Integer> are both just a List. This process is called type erasure, and it's the reason behind almost every "why can't I do that?" moment with generics: no new T(), no List<int>, no instanceof List<String>.

Java chose erasure in 2004 for compatibility: code compiled with generics had to run on the same JVM and interoperate with millions of lines of pre-generics libraries. Knowing how erasure works lets you predict exactly what's legal, apply the standard workarounds, and avoid a subtle bug called heap pollution. This lesson builds on Generics and Bounded Types and Wildcards.

What erasure does

When the compiler translates a generic class or method, it:

  1. Replaces each type parameter with its erasure: the leftmost bound, or Object if there is none. T becomes Object; T extends Comparable<T> becomes Comparable; T extends Number & Comparable<T> becomes Number.
  2. Inserts casts where a value of a type parameter is used as a specific type, such as the (String) on names.get(0).
  3. Generates bridge methods when needed to keep overriding working (shown below).

So this source code:

Java
class Box<T extends Comparable<T>> {
    private T value;
    T get() { return value; }
}

Box<String> box = ...;
String s = box.get();

compiles to roughly what you'd have written by hand before Java 5:

Java
class Box {
    private Comparable value;
    Comparable get() { return value; }
}

Box box = ...;
String s = (String) box.get();     // cast inserted by the compiler

The cast can never fail as long as your code compiles without unchecked warnings. That's the guarantee generics give you.

One class at runtime

Because of erasure, every parameterization of a generic class shares one runtime class. The type arguments aren't stored in the object:

Java Erased type arguments at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

ArrayList<String> and ArrayList<Integer> have the same Class object. That's why instanceof List<String> is a compile error: at runtime there's nothing that could tell a list of strings from a list of integers. instanceof List<?> is fine because it only asks the question the JVM can answer.

The cast (List<String>) unknown is an unchecked cast: the JVM only checks that the object is a List, and the compiler warns that the <String> part can't be verified. Here it was a lie, which is the start of heap pollution, covered later.

There is one exception to "type arguments are gone". instanceof is allowed with a generic type when the compiler can prove it's safe from the static type, e.g. Collection<String> c = ...; if (c instanceof List<String> l). The runtime still only checks List; the <String> part is known from the declaration.

Erased signatures, kept metadata, and bridge methods

Erasure removes type arguments from objects, but declarations keep them in the class file as metadata. Reflection can read the generic type of a field, method parameter or superclass, which is how libraries like Jackson know that a field List<Address> addresses holds addresses. You can also see the bridge method the compiler adds when a class implements a generic interface:

Java Reflection sees erased and generic signatures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Comparable<Version> erases to Comparable, whose method is compareTo(Object). Your record only declares compareTo(Version), which would not override the erased method. So the compiler adds a synthetic bridge, compareTo(Object), that casts its argument to Version and calls your method. That's why a raw Comparable call with a String fails with a ClassCastException instead of silently doing something wrong. (The raw Comparable call also makes the compiler print an [unchecked] warning under the editor, which is exactly the warning such code deserves.)

The limitations, and the workarounds

Each limitation follows from one fact: at runtime, the JVM doesn't know what T is.

No new T()

new T() doesn't compile, because the JVM wouldn't know which constructor to call. Pass in a factory instead, usually a Supplier<T> with a constructor reference:

Java
static <T> List<T> createMany(int count, Supplier<T> factory) {
    List<T> result = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        result.add(factory.get());
    }
    return result;
}

List<StringBuilder> builders = createMany(3, StringBuilder::new);

No new T[] and no generic array creation

new T[10] and new List<String>[10] are illegal. Arrays check every store at runtime (Generics showed ArrayStoreException), and an array created without knowing its real element type can't do that. Options:

  • Use a List<T> instead of an array (almost always the best choice).
  • Ask the caller for an array constructor, IntFunction<T[]>, the way Collection.toArray(String[]::new) works.
  • Ask for a Class<T> and call java.lang.reflect.Array.newInstance.

No primitive type arguments

List<int> doesn't compile because an erased type parameter becomes Object (or its bound), and an int is not an object. Use wrapper types (List<Integer>), or the primitive specializations the JDK provides for speed: IntStream, IntFunction, ToIntFunction and friends (Functional Interfaces).

No instanceof T, no T.class, no catching T

x instanceof T, T.class and catch (T e) all need the runtime type. When you need it, pass a type token, a Class<T> object, and use its isInstance and cast methods:

Java Workarounds: Supplier, array constructor, Class token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

firstN returns a genuine String[], not an Object[] pretending to be one, because the caller supplied the array constructor. Class tokens can't express List<String> (there's no List<String>.class); libraries like Jackson solve that with "super type tokens", anonymous subclasses such as new TypeReference<List<Address>>() {} whose generic superclass survives in the metadata you saw above.

No static members of type T

A static field belongs to the class, and all parameterizations share one class, so static T defaultValue; is a compile error: Box<String> and Box<Integer> would have to share the same field. Static generic methods are fine, since they declare their own type parameters.

No overloads that differ only in type arguments

These two methods erase to the same signature, print(List), so the class can't have both:

Java
void print(List<String> words) { ... }
void print(List<Integer> numbers) { ... }   // error: name clash, both have the same erasure

Give them different names (printWords, printNumbers) instead.

No generic exception classes

class ParseError<T> extends Exception is illegal. A catch clause has to check the exception type at runtime, and ParseError<String> and ParseError<Integer> would be indistinguishable.

Heap pollution

Heap pollution happens when a variable of a parameterized type refers to an object that isn't of that type, for example a List<String> that actually contains an Integer. It can only happen through code that produced an unchecked warning: raw types, unchecked casts, or generic varargs. The nasty part is where the error appears: not where the bad element got in, but later, at a compiler-inserted cast in innocent-looking code.

Generic varargs are the sneakiest source. A varargs parameter T... items is really an array, and since Java can't create a T[], the compiler creates an array of the erasure, here Object[]:

Java Heap pollution through generic varargs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This program fails on purpose. Called directly, asArray("red", "blue") gets a real String[]. Called from inside the generic pickTwo, where T is unknown, the compiler can only create an Object[]. Assigning it to String[] triggers the inserted cast, and the program crashes with a ClassCastException saying class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; (the JVM's names for Object[] and String[]) on a line that contains no visible cast at all.

@SafeVarargs

Every method with a generic varargs parameter makes the compiler warn about "possible heap pollution". The annotation @SafeVarargs tells it that the method is safe, which silences the warning at the declaration and at every call site. The promise is true when the method:

  • doesn't store anything into the varargs array, and
  • doesn't let a reference to the array escape (doesn't return it or hand it to untrusted code).

Reading the elements is always fine. List.of(E... elements), Set.of, EnumSet.of and Arrays.asList are all annotated this way. The asArray method above breaks the second rule, so its @SafeVarargs is a lie, which is exactly what makes the crash possible.

@SafeVarargs can only be placed on methods that can't be overridden: static methods, final instance methods, private instance methods (Java 9+) and constructors.

Java A varargs method that really is safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

These methods copy elements out of the array into a fresh list and never return the array itself, so callers get correctly typed results whatever T turns out to be.

Why not reified generics?

Languages like C# keep type arguments at runtime ("reified generics"), which allows new T() and is List<string>. Java's designers chose erasure so that generic and pre-generic code could mix freely and existing JVMs and libraries kept working. The trade-off holds up well in practice: the compile-time checks catch the vast majority of errors, and the workarounds above cover the rest. Project Valhalla is exploring generics over primitive-like value types for a future release, but erasure of reference type arguments is here to stay.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass() evaluate to?

    Type arguments are erased, so every ArrayList shares the same runtime class.
  2. 2. What is the erasure of T in class Range<T extends Number & Comparable<T>>?

    A type parameter erases to its leftmost bound. Here that's Number; Object is used only when there's no bound.
  3. 3. Which is the standard workaround for new T() in a generic method?

    T.class doesn't exist and casting a plain Object is wrong. A Supplier, often a constructor reference like StringBuilder::new, lets the caller decide how to create objects.
  4. 4. Why can't a class declare both void save(List<String> a) and void save(List<Integer> b)?

    After erasure both methods have the signature save(List). The compiler reports a name clash because the JVM couldn't tell them apart.
  5. 5. When is @SafeVarargs on static <T> void log(T... values) a true promise?

    The varargs array may really be an Object[]. Reading is safe; writing into it or letting it escape can cause heap pollution and ClassCastExceptions elsewhere.

Summary

  • Generics are checked at compile time and then erased: type parameters become their leftmost bound (or Object), and the compiler inserts casts and bridge methods.
  • All parameterizations share one runtime class, so instanceof List<String> and unchecked casts can't be verified; instanceof List<?> works.
  • Declarations keep generic signatures as metadata, which reflection and libraries like Jackson can read.
  • Not allowed: new T(), new T[], primitive type arguments, T.class, instanceof T, static fields of type T, overloads that differ only in type arguments, and generic exception classes.
  • Workarounds: Supplier<T>, IntFunction<T[]> (like String[]::new), Class<T> tokens, List instead of arrays, wrapper types or primitive streams.
  • Heap pollution comes from raw types, unchecked casts and generic varargs; mark varargs methods @SafeVarargs only when they never write to or expose the array.

Next: Lambda Expressions, where you'll pass behavior around as compact functions, like the Supplier and IntFunction arguments you just used.