Course contentsShow
← Java
Lesson 891 of 2,87021. Generics FundamentalsFree lesson

What Is Type Erasure?

Understanding that Java removes generic type information at compile time, replacing type parameters with their bounds or Object.

What Is Type Erasure?

You'll learn why generic type information disappears from your compiled Java code and what replaces it.


Understanding Type Erasure

Type erasure is Java's mechanism for implementing generics. At compile time, the Java compiler removes all generic type information from your code—it literally "erases" the type parameters. After compilation, your generic classes and methods look like they never used generics at all.

Here's what happens: the compiler replaces every type parameter (like T) with its bound (the type constraint, if any) or with Object if no bound exists. It also inserts type casts wherever necessary to maintain type safety.

This erasure is why you've seen those compiler warnings about raw types and unchecked operations—the runtime has no generic type information to verify!


Why Java Does This

Java introduced generics in Java 5, but needed backward compatibility with pre-generics code. Type erasure ensures that generic code can run on older JVMs and interoperate seamlessly with raw types. The cost? No generic type information exists at runtime.


What Gets Erased

Think of it like writing a letter in pencil, then erasing the specific details before sending:

  • ArrayList<String> becomes ArrayList (holding Object references)
  • Box<Integer> becomes Box (with Object fields)
  • Type casts are automatically inserted by the compiler when you retrieve values

The compiler does all the type-checking work, then throws away the evidence.


The Consequence

Because types are erased, you cannot check the type parameter at runtime—instanceof T doesn't work, and new T() is forbidden. The JVM simply doesn't know what T was.

Key Takeaway: Type erasure removes all generic type parameters at compile time, replacing them with Object or their bounds, which ensures backward compatibility but eliminates runtime type information.