Type erasure

At compile-time, the compiler has full type information available but this information is intentionally dropped in general when the byte code is generated, in a process known as type erasure

Why?

This is done this way due to compatibility issues. When generics was introduced in Java 5, they have to make sure full backward compatibility with this kind of non-generic code

List<Dog> myList = new ArrayList<>();
myList.add(new Dog("Rex"));
Dog dog = myList.get(0);

After compilation, they are erased and replaced with raw type and casting, the generated byte code is almost the same as pre-Java 5 code. After compilation, type erasure converts the sugar to non-generic compliant code.

List myList = new ArrayList(); // No longer <Dog>
myList.add(new Dog("Rex"));
Dog dog = (Dog) myList.get(0);

The type information isn’t longer available at the runtime.

Consequences

  • At execution time, a List<String> and a List<Date> are exactly the same; the extra type information has been erased by the compiler.