Type Erasure and Raw Types

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

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

  1. Distinguish between compile-time and runtime type information.
  2. Explain the purpose of synthetic bridge methods.
  3. 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

University approvals: 0
Tasks
Question 1

Why does new T() fail for a type parameter T?

Question 2

Why can a Raw Type trigger an error far from the unsafe writing?

Question 3

Implement a generic Pair class with two access methods.

Hint

The type parameters A and B can directly serve as return types. Access the instance methods using this.first and this.second.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy