Q33: What is Type Erasure in Java Generics?

Java Generics were introduced in Java 5 with backward compatibility. Type Erasure means the Java compiler removes all generic type parameters during compilation, replacing bounded parameters with their bound (e.g., T -> Object or Comparable) and inserting explicit casts. At runtime, bytecode contains no generic type information.

Type Erasure Translation
// Written Code
List<String> list = new ArrayList<>();
list.add("Java");
String s = list.get(0);

// Compiled Bytecode Equivalent (Erased)
List list = new ArrayList();
list.add("Java");
String s = (String) list.get(0); // Cast inserted by compiler
💡 The compiler erases String type parameters and inserts explicit target type casts.
Key Takeaways
  • Generic type information exists ONLY at compile time; erased in bytecode.
  • Cannot instantiate generic arrays (new T[]) or primitive generics (List<int>).
Knowledge Check

Can you check runtime types using instanceOf with explicit generics (e.g. obj instanceof List<String>)?