Repaso
EspaƱol
Java CoreIntermediateJV-17

What is type erasure in Java generics?

Options

  1. Generics are erased at runtime, so List<String> is List (Correct option)
  2. Generic types are erased from the source code after compiling
  3. Java deletes any generic class that nobody uses anywhere
  4. 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.

Key terms

Practice this question in Repaso