Type erasure
- Java course
- Intermediate
- Lesson 86/116
- 5 min
Learn post-compile type erasure.
What is type erasure?
Java generics are checked at compile time; at runtime the type info is erased. This is called type erasure. A List<String> and a List<Integer> become the same List class after compilation.
This is why new ArrayList<String>().getClass() and new ArrayList<Integer>().getClass() return the same result. At runtime there are no generic type parameters; only the raw type runs. This was designed for backward compatibility with the JVM.
Erasure limitations
Type erasure blocks some things. At runtime you cannot write (obj instanceof List<String>); only (obj instanceof List<?>) or (obj instanceof List) is valid. Also you cannot create an instance of a generic type with new T().
Generic arrays are not allowed either: new List<String>[10] is forbidden. These follow directly from erasure; because the type parameter is unknown at runtime the JVM cannot do the right check. To work around these limits you pass a Class<T> token or use nested collections like List<List<String>>.
Practice Demonstrate type erasure
In main, create List<String> strings = new ArrayList<>(); and List<Integer> numbers = new ArrayList<>();. Compare the two getClass() calls with == and print the result with System.out.println(strings.getClass() == numbers.getClass());.
Starter code
import java.util.ArrayList;
import java.util.List;
// Create two different List<T> instances
// getClass() comparison and printlnSample solution
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
System.out.println(strings.getClass() == numbers.getClass());
}
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ArrayList instance
List<String> strings = new Array____<>();
List<String> strings = new ArrayList<>();
Explanation: ArrayList is the standard implementation of List.
2 Match the type erasure concepts
| Term | Meaning |
|---|---|
type erasure |
Removal of type info |
getClass() |
Returns runtime type |
<T> |
Compile-time info |
raw type |
Type without parameter |
3 What is forbidden due to type erasure?
- Declaring List<Integer>
- Creating a generic instance with new T() Correct answer
- Calling a generic method
- Defining a generic class
Explanation: new T() is forbidden because T is unknown at runtime.