What is type erasure in Java generics?
Options
- Generics are erased at runtime, so
List<String>isList(Correct option) - Generic types are erased from the source code after compiling
- Java deletes any generic class that nobody uses anywhere
- Generics make the program slower, as types are checked later
Answer
Generic type information is removed by the compiler; at runtime a List<String> and a List<Integer> are both just List
Why
Generics (List<String>) let the compiler check types so you do not need casts. After checking, the compiler removes (erases) the type arguments and keeps only the raw type in the bytecode.
Consequences: you cannot write new T(), instanceof List<String>, or create new T[10], and List<int> is not allowed because type arguments must be objects.
Remember
Generics are a compile-time check only.