Type Erasure and Raw Types
Type Erasure: Type parameters are removed or replaced by bounds at runtime. Therefore, new T() and arrays of T are problematic.
Raw Types (List without <...>) exist for legacy code. The compiler warns; you lose type checking.
In new code, avoid Raw Types and work with parameterized types.
Erasure of type parameters: JLS 4.6 [1].
$$\mathrm{erase}(\mathtt{List\lt E\gt })=\mathtt{List}$$
Where used
This explains ClassCastExceptions at runtime, why new T() is absent, and why Reflection/Serialization loses Generics. Raw Types in legacy code are a migration issue, not a modern API form.
Depth
Java translates most generic type information into checks and conversions at compile time. At runtime, different type argument instantiations usually share the same class representation. This translation is called type erasure.
Bridge methods maintain polymorphism when specialized method signatures do not match directly after translation. Runtime information about nested type arguments is only partially available via Reflection.
A Raw Type bypasses part of the static checks for compatibility with older code. Unsafe write access and later casting can be far apart, leading to errors in misleading locations.
Difficulty levels
- Distinguish between compile-time and runtime type information.
- Explain the purpose of synthetic bridge methods.
- Trace a Raw Type warning to a later error.
Pitfalls
instanceof List<String> is not permissible due to missing complete runtime information. Suppressed warnings are not proof of type safety.
Sources
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users