Java Generics and Type Erasure
Fast recall
Quick revision
Core answer
Whether you understand why generics exist, what guarantees they give, and what the erasure tradeoff costs you at runtime
Confusing compile-time safety with runtime information — claiming you can do instanceof checks on generic types or create generic arrays
Explain why List<String> and List<Integer> share the same Class object at runtime, describe how to work around erasure with Class<T> tokens and super type tokens, and mention bounded wildcards for API design
Interview-ready guide
Interview answer
Generics give you compile-time type safety — List won't accept an Integer and the compiler inserts casts for you. The tradeoff is type erasure: after compilation, List and List are both just List.
Consequences of erasure:
- No
instanceof List— the type parameter doesn't exist at runtime - No
new T[]ornew T()— the JVM doesn't know whatTis at runtime - Workaround: pass a
Classtoken and useArray.newInstance(clazz, length)or reflection
What survives erasure:
- Bounded types erase to their bound:
becomesNumberin bytecode, notObject - Bridge methods are generated when a generic class is subclassed with a concrete type, maintaining polymorphism
Wildcards (PECS):
List extends Number>acceptsListorList— for reading (Producer Extends)List super Integer>acceptsListorList— for writing (Consumer Super)- Generic collections are invariant without wildcards:
Listis NOT aList
I recommend following PECS for any generic API that accepts or returns collections.
Java Generics and Type Erasure
Direct Answer
Generics let you parameterize classes and methods with type variables (e.g., List<T>) so the compiler enforces type safety at compile time. Type erasure means the compiler removes those type parameters at bytecode level, replacing them with Object (or their bounds), so generic information does not exist at runtime.
Common Mistakes & Pitfalls
Confusing compile-time safety with runtime information — claiming you can do instanceof checks on generic types or create generic arrays
Check your understanding
Answer these without looking back at the article.
- What is the difference between ? extends T and ? super T (PECS)?
- Why can't you create a generic array in Java?
- How does Jackson's TypeReference work around type erasure?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.