Sobes.tech
Middle+

Mis on tüübi kustutamine Java's?

sobes.tech AI

Vastus AI-lt

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 bound (usually Object) and inserts necessary type 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 a parameterized type (e.g., if (list instanceof List<String>)).
    • Methods cannot be overloaded based on parameterized types if their signatures after erasure 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.