Provide Best Programming Tutorials

Erasure and Restrictions on Generics

Erasure and Restrictions on Generics

The information on generics is used by the compiler but is not available at runtime.

This is called type erasure.

Generics are implemented using an approach called type erasure : The compiler uses the generic type information to compile the code, but erases it afterward. Thus, the generic information is not available at runtime. This approach enables the generic code to be backward compatible with the legacy code that uses raw types.

The generics are present at compile time. Once the compiler confirms that a generic type is used safely, it converts the generic type to a raw type. For example, the compiler checks whether the following code in (a) uses generics correctly and then translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.



  • Restriction 1: Cannot Use new E()

  • Restriction 2: Cannot Use new E[]

  • Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context

  • Restriction 4: Exception Classes Cannot Be Generic


  1. What is erasure? Why are Java generics implemented using erasure?

  2. If your program usesArrayList<String> andArrayList<Date>, does the JVM load both of them?

  3. Can you create an instance using new E() for a generic type E? Why

  4. Can a method that uses a generic class parameter be static? Why?

  5. Can you define a custom generic exception class? Why?

Leave a Reply

Close Menu