What is type erasure in Java generics?

Generics are checked by the compiler, and then the type arguments are erased. At run time a List<String> is only a List. This keeps old code working, but it has effects:

  • You can not write new T(), T.class or instanceof List<String>.
  • You can not make an array of a generic type: new List<String>[10].
  • Primitives are not allowed as type arguments.
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());
        System.out.println(strings.getClass().getName());
    }
}
Output

true
java.util.ArrayList

See Java Generics.


Learn more about the similar topics:
Tutorials
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?