Sobes.tech
Middle+

What is type erasure in Java?

sobes.tech AI

Answer from AI

Type erasure is a process in Java where type information is removed at compile time, and the compiled bytecode does not contain information about generic parameters.

Key points:

  • Compatibility: Allows generics to work with older code that does not use generics.
  • Implementation: The compiler replaces parameterized types with their upper bounds (usually Object) and inserts necessary casts.
  • Limitations:
    • Primitive types cannot be used as generic parameters (e.g., List<int>).
    • You cannot create an array of a parameterized type (e.g., new List<String>[10]).
    • You cannot use the instanceof operator to check for a parameterized type (e.g., if (list instanceof List<String>)).
    • Methods cannot be overloaded based on parameterized types if their erased signatures are the same.

Example:

// Source code with generics
List<String> stringList = new ArrayList<>();
stringList.add("hello");
String s = stringList.get(0); // No explicit cast needed

// Bytecode after type erasure
List list = new ArrayList(); // Type List<String> replaced with List
list.add("hello");
String s = (String)list.get(0); // Implicit cast inserted

Despite limitations, type erasure is a key aspect of implementing generics in Java, ensuring backward compatibility.

What is type erasure in Java? — Java - sobes.tech