I read a tweet today that said:
It\'s funny when Java users complain about type erasure, which is the only thing Java got right, while ignoring all th
(Although I already wrote an answer here, revisiting this question two years later I realize there is another, completely different way of answering it, so I'm leaving the previous answer intact and adding this one.)
It is highly arguable whether the process done on Java Generics deserves the name "type erasure". Since generic types are not erased but replaced with their raw counterparts, a better choice seems to be "type mutilation".
The quintessential feature of type erasure in its commonly understood sense is forcing the runtime to stay within the boundaries of the static type system by making it "blind" to the structure of the data it accesses. This gives full power to the compiler and allows it to prove theorems based on static types alone. It also helps the programmer by constraining the code's degrees of freedom, giving more power to simple reasoning.
Java's type erasure does not achieve that—it cripples the compiler, like in this example:
void doStuff(List collection) {
}
void doStuff(List collection) // ERROR: a method cannot have
// overloads which only differ in type parameters
(The above two declarations collapse into the same method signature after erasure.)
On the flip side, the runtime can still inspect the type of an object and reason about it, but since its insight into the true type is crippled by erasure, static type violations are trivial to achieve and hard to prevent.
To make things even more convoluted, the original and erased type signatures co-exist and are considered in parallel during compilation. This is because the whole process is not about removing type information from the runtime, but about shoehorning a generic type system into a legacy raw type system to maintain backwards compatibility. This gem is a classic example:
public static > T max(Collection extends T> coll)
(The redundant extends Object
had to be added to preserve backward compatibility of the erased signature.)
Now, with that in mind, let us revisit the quote:
It's funny when Java users complain about type erasure, which is the only thing Java got right
What exactly did Java get right? Is it the word itself, regardless of meaning? For contrast take a look at the humble int
type: no runtime type check is ever performed, or even possible, and the execution is always perfectly type-safe. That's what type erasure looks like when done right: you don't even know it's there.