What is the concept of erasure in generics in Java?
To complete the already very complete Jon Skeet's answer, you have to realize the concept of type erasure derives from a need of compatibility with previous versions of Java.
Initially presented at EclipseCon 2007 (no longer available), the compatibility included those points:
Original answer:
Hence:
new ArrayList() => new ArrayList()
There are propositions for a greater reification. Reify being "Regard an abstract concept as real", where language constructs should be concepts, not just syntactic sugar.
I should also mention the checkCollection method of Java 6, which returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException
.
The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts.
Usually this is not a problem, as the compiler issues warnings on all such unchecked operations.
There are, however, times when static type checking alone is not sufficient, like:
ClassCastException
, indicating that an incorrectly typed element was put into a parameterized collection. Unfortunately, the exception can occur at any time after the erroneous element is inserted, so it typically provides little or no information as to the real source of the problem.Update July 2012, almost four years later:
It is now (2012) detailed in "API Migration Compatibility Rules (Signature Test)"
The Java programming language implements generics using erasure, which ensures that legacy and generic versions usually generate identical class files, except for some auxiliary information about types. Binary compatibility is not broken because it is possible to replace a legacy class file with a generic class file without changing or recompiling any client code.
To facilitate interfacing with non-generic legacy code, it is also possible to use the erasure of a parameterized type as a type. Such a type is called a raw type (Java Language Specification 3/4.8). Allowing the raw type also ensures backward compatibility for source code.
According to this, the following versions of the
java.util.Iterator
class are both binary and source code backward compatible:
Class java.util.Iterator as it is defined in Java SE version 1.4:
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
Class java.util.Iterator as it is defined in Java SE version 5.0:
public interface Iterator {
boolean hasNext();
E next();
void remove();
}