Type erasure and generic limits
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Type erasure is how Java compiles generics: the Java compiler (javac) uses the type arguments to check your code, then removes them and adds the casts itself. At run time a Box<String> and a Box<Integer> are the same plain Box, and that one fact explains every limit of generics.
What type erasure means
Type erasure is how the Java compiler handles generics: it checks the code using the type arguments, then removes them from the compiled program. T becomes Object (or its bound) and a cast is added wherever a value comes out, so generic types exist only at compile time.
After compiling, the <String> part is removed and Java adds the cast for you. So the program that runs is the old Object box with casts, written for you by the compiler.
// What you writeBox<String> box = new Box<>();box.set("Laptop");String name = box.get();
// What runs after compilingBox box = new Box();box.set("Laptop");String name = (String) box.get();Example 1 · One class at run time
class Box<T> { private T value;
void set(T value) { this.value = value; }
T get() { return value; }}
public class OneClassDemo { public static void main(String[] args) { Box<String> product = new Box<>(); Box<Integer> price = new Box<>();
System.out.println(product.getClass().getName()); System.out.println(price.getClass().getName()); System.out.println(product.getClass() == price.getClass()); }}Box Box true
What this code does
getClass()asks the running object for its class, as in The Object class (opens in a new tab). Both answer plainBox: no<String>or<Integer>survives.Box<String>andBox<Integer>share one.classfile and one class at run time, so==on the two classes istrue.
Java chose erasure in 2004 so that new generic code and old raw code could run together on the same JVM, with no change to old class files. The cost is that the JVM never knows a box's type argument, which the next sections show.
What T becomes, and the hidden cast
The erasure of a type parameter is the type the Java compiler puts in its place: Object for a plain T, and the first bound for a bounded one. So <T extends Number> erases to Number and <T extends Comparable<T>> to Comparable.
The cast the Java compiler adds is real. Let a wrong value slip past the Java compiler through a raw variable, and the crash appears on a line with no cast in it.
Example 2 · The hidden cast
class Box<T> { private T value;
void set(T value) { this.value = value; }
T get() { return value; }}
public class HiddenCastDemo { public static void main(String[] args) { Box<String> product = new Box<>(); Box raw = product; raw.set(40); System.out.println("Stored something"); String name = product.get(); System.out.println(name); }}Stored something Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap') at HiddenCastDemo.main(HiddenCastDemo.java:19)
What this code does
Box raw = product;is a raw type, soraw.set(40)gets only an unchecked warning, and anIntegerlands in aBox<String>. Now the box holds the wrong type.String name = product.get();has no cast in the source, yet it throws aClassCastException: the(String)that the Java compiler added runs and fails.- The lesson: never mix raw types with generic ones, and treat every "unchecked" warning as a bug.
A bounded T erases to its bound, which is why doubleValue() on a <T extends Number> still works at run time: the field or parameter really is a Number in the compiled program.
What you cannot do with T
Every limit has the same cause: at run time T is gone, so Java cannot do anything that needs to know what T really is.
Example 3 · new T() and new T[] do not compile
class Tray<T> { private T item = new T(); private T[] items = new T[10];}
public class NewTDemo { public static void main(String[] args) { System.out.println("never runs"); }}NewTDemo.java:2: error: unexpected type
private T item = new T();
^
required: class
found: type parameter T
where T is a type-variable:
T extends Object declared in class Tray
NewTDemo.java:3: error: generic array creation
private T[] items = new T[10];
^
2 errorsWhat this code does
new T()needs a real class to call a constructor on. After erasureTis justObject, and the Java compiler cannot even promise thatThas a constructor with no parameters.new T[10]would need the element type at run time to build the array, and it is erased: "generic array creation".
Example 4 · instanceof Box<String> and a static T do not compile
class Box<T> { static T lastUsed;}
public class LimitsDemo { public static void main(String[] args) { Object o = new Box<String>(); if (o instanceof Box<String>) { System.out.println("a box of strings"); } }}LimitsDemo.java:2: error: non-static type variable T cannot be referenced from a static context
static T lastUsed;
^
LimitsDemo.java:8: error: Object cannot be safely cast to Box<String>
if (o instanceof Box<String>) {
^
2 errorsWhat this code does
- One
staticfield is shared by everyBox<String>,Box<Integer>and so on, so it cannot have the typeT, which differs per object. o instanceof Box<String>asks the JVM a question it cannot answer: the object only knows it is aBox. So the Java compiler says anObject"cannot be safely cast to Box<String>";o instanceof Box<?>compiles.
The last limit you already know from Write a generic class (opens in a new tab): Box<int> is not allowed, because an erased T must hold an Object, and an int is not one.
Workarounds real code uses
Real code works around these limits in two common ways: pass in something that can make a T, or store the items in an Object[] and cast them on the way out.
Example 5 · Workarounds: a maker and an Object[] store
interface Maker<T> { T make();}
class Product { String name; int price;
Product(String name, int price) { this.name = name; this.price = price; }}
class Shelf<T> { private Object[] items = new Object[3]; private int count = 0;
void fill(Maker<T> maker) { while (count < items.length) { items[count] = maker.make(); count++; } }
@SuppressWarnings("unchecked") T get(int i) { return (T) items[i]; }}
public class WorkaroundDemo { public static void main(String[] args) { Shelf<String> boxes = new Shelf<>(); boxes.fill(() -> "Gift box"); System.out.println(boxes.get(0) + ", " + boxes.get(2));
Shelf<Product> trays = new Shelf<>(); trays.fill(() -> new Product("Phone", 15000)); System.out.println(trays.get(1).name + ", Rs. " + trays.get(1).price); }}Gift box, Gift box Phone, Rs. 15000
What this code does
Maker<T>is a tiny interface whosemake()creates aT. The caller passes a lambda such as() -> "Gift box", as in Functional interfaces and lambdas (opens in a new tab), soShelfnever needsnew T().- The items live in an
Object[], which is allowed.getcasts back with(T); the Java compiler cannot check that cast and warns "unchecked". @SuppressWarnings("unchecked")says you checked it yourself: onlyfillputs values in, and they are alwaysT.
This is how ArrayList<E> works inside: an Object[] plus casts, as ArrayList internals (opens in a new tab) shows. For an instanceof check, use o instanceof Box<?>, as in instanceof (opens in a new tab).
Overloading clash after erasure
Two methods that differ only in their type arguments look different to you, but not after erasure. Both become print(Box), so the Java compiler refuses them.
Example 6 · Overloading clash after erasure
class Box<T> { private T value;
void set(T value) { this.value = value; }
T get() { return value; }}
public class ClashDemo { static void print(Box<String> product) { System.out.println("Product: " + product.get()); }
static void print(Box<Integer> price) { System.out.println("Price: " + price.get()); }
public static void main(String[] args) { System.out.println("never runs"); }}ClashDemo.java:18: error: name clash: print(Box<Integer>) and print(Box<String>) have the same erasure
static void print(Box<Integer> price) {
^
1 errorWhat this code does
- "name clash ... have the same erasure": after erasure both methods are
print(Box). - Overloading needs different parameter types after erasure, and
Box<String>andBox<Integer>are both justBox.
After erasure both headers are static void print(Box), two methods with one signature, which overloading (opens in a new tab) never allows. Give them different names, such as printProduct and printPrice.
Next step
Check your understanding
12 quick questions