SteelReed

Search

Search posts, questions…

Java CoreQuestion 29 / 43

Middle

What is type erasure and what limitations does it bring?

Short answer

Type erasure: the compiler checks generic types, then erases them. At runtime List<String> and List<Integer> are the same class.

javac checks typesSource: List of StringErase type argumentsT becomes ObjectBytecode: raw List+ inserted castsRuntime: one List classfor every TNo new T()no new T[n]

3 points to say:

  1. Erasure keeps pre-Java 5 code working alongside new code.
  2. So you can't write new T() or new T[n].
  3. To know the type at runtime, pass a Class<T> or Supplier<T>.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.