Generics: Type Erasure in Java

Before we dwell into the concept of “Type Erasure”, let us have a look into the below code.

Mixing Generic and Non-generic Collections

Screen Shot 2018-11-04 at 12.27.19 PM

Do we think, the above will compile and execute correctly.

Surprise surprise, the output is :[5, 50, ABC]

It means, we were able to put a String into a Integer List. How was it possible?
The magic is due to the Type Erasure.

The JVM has no idea that your ArrayList was supposed to hold only Integers. The typing information does not exist at runtime! All your generic code is strictly for the compiler. Through a process called “type erasure,” the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode.

At runtime, ALL collection code—both legacy and new Java 5 code you write using generics—looks exactly like the pre-generic version of collections. None of your typing information exists at runtime.

In other words, even though you WROTE
List myList = new ArrayList();

By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:
List myList = new ArrayList();

Think of generics as strictly a compile-time protection. The compiler uses generic type information (the in the angle brackets) to make sure that your code doesn’t put the wrong things into a collection, and that you do not assign what you get from a collection to the wrong reference type. But NONE of this protection exists at runtime.

Why did they do generics this way? Why is there no type information at runtime?
To support legacy code.At runtime, collections are collections just like the old days.

Leave a Reply

Your email address will not be published. Required fields are marked *