Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Type Erasure

โญโญ intermediateโณ 13 min read๐Ÿ“ Lesson 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; use ArrayList<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.

โšก Now practice

Ready to Code
Generics LabPECS signatures in action, a Comparable-bounded max, and the Class-token erasure workaround.
3 challenges ยท ยท ~40 min