Type Erasure
intermediate13 min readLesson 73 of 180
Why List<String> and List<Integer> are one class at runtime, and the compile rules erasure forces on arrays, overloads, and instanceof.
Type erasure โ what generics really are
Generics exist at compile time only. List<String> and List<Integer>
are the same class at runtime โ both erase to List. Consequences:
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
a.getClass() == b.getClass() // true!
// can't do these:
// new T[10] โ no T at runtime
// if (x instanceof List<String>) โ erased
// catch (MyEx<String> e) โ generics in catch are banned
Practical rules:
- Arrays of generic type are unsafe (
new T[10]won't compile; useArrayList<T>) - You cannot overload on erased parameters:
f(List<String>)+f(List<Integer>)โ same erasure, compile error - Need runtime type info? Pass a
Class<T>token:<T> T parse(String s, Class<T> type)
Erasure explains why wildcards exist: flexibility must be expressible in the type system without runtime cost.