What is type erasure in Java, and what does it mean for your code at run time?
Type erasure is the rule that says the compiler throws away the type information when it builds the class file.
So a list of strings and a list of numbers are the very same class inside the virtual machine. The angle brackets are a promise that the compiler keeps for you while it checks your code, and then it takes the promise away before the program runs.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
// At run time they are the same class.
System.out.println("the class of the names : " + names.getClass().getName());
System.out.println("the class of the numbers : " + numbers.getClass().getName());
System.out.println("the same class : " + (names.getClass() == numbers.getClass()));
// The compiler still checks the types while it compiles.
// names.add(42); // this does not compile
names.add("Ada");
System.out.println("the list holds : " + names);
}
}
So what does it mean for your code at run time? Three things.
The first one is that the type information is not there any more. If you ask a list what class it is, it says java.util.ArrayList and nothing about what it holds. You cannot ask a running program what type its list contains.
The second one is that a bounded type parameter loses its bound at run time. The declaration <T extends Number> becomes simply Number in the class file, so the compiler can still check that a number is passed in, but the information about the exact type is gone.
The third one is that a cast to a parameterised type cannot be checked. When you take an object out of a collection whose type was erased, the compiler has to warn you, because it cannot prove that the object really is the type that you claim. That is what the warning about an unchecked cast means.
The next question in this topic looks at the rule that erasure forces on you.