Java · OOP, JVM and backend craft
How do generics work in Java and what is type erasure?
Short answer
Generics provide compile-time type safety and eliminate casts, but they are erased at runtime. That affects overload resolution, instanceof checks, arrays and how wildcards express variance.
A type parameter is checked by the compiler and then replaced by its bound, usually Object, in the generated bytecode. The JVM does not retain the type argument for ordinary generic classes. This is type erasure, and it exists mainly for backward compatibility with pre-generics code.
public final class Box<T> {
private final T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
public static void copy(List<? extends Number> source,
List<? super Number> target) {
for (Number number : source) {
target.add(number);
}
}
}What erasure implies
- You cannot write new T() without passing a Class token or factory
- You cannot use instanceof List<String> or create a T array directly
- Overloads that differ only by type argument clash after erasure
- Generic types are invariant: List<Integer> is not a List<Number>
- Wildcards restore flexibility for producers and consumers
Generic arrays and varargs can cause heap pollution warnings. Prefer List<T> over T arrays, and annotate a genuinely safe varargs method with @SafeVarargs. Never suppress unchecked warnings without understanding the concrete failure mode.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the PECS rule?
- 2Why can't you create a generic array?
- 3What is heap pollution?
- 4Why is List<Integer> not a subtype of List<Number>?
Say it in the interview
Generics give compile-time type checks and remove manual casts, but the type argument is erased at runtime, usually to its bound. That means no instanceof List of String and no new T without extra information. I use wildcards with the PECS rule: extends for reading, super for writing. I also prefer lists to generic arrays, because arrays are reified and generics are not, which creates heap pollution risks.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.