Java Generics
Compile-time type safety over a runtime that erases it. Almost every confusing generics error traces back to erasure or to variance.
4 concepts · 12 interview questions
What this topic covers
Every concept in generics, and the questions each one gets asked as. Where a question links, it has a full write-up.
Type parameters and bounds
A parameter standing in for a type, optionally bounded so the code can call methods on it.
- Why use generics instead of Object?
- What does <T extends Comparable<T>> mean?
- What is a generic method, and when is one needed?
Type erasure
Generic types exist only at compile time; the bytecode sees the erased bound. That is why you cannot use instanceof or new on a type parameter.
- What is type erasure, and what does it prevent?
- Why can't you create new T[] or call instanceof T?
- Why can't a class implement both Comparable<A> and Comparable<B>?
Variance and wildcards
Generics are invariant: List<String> is not a List<Object>. Wildcards reintroduce controlled variance — extends to read, super to write.
- Why is List<String> not a List<Object>?
- What is PECS?
- What can you do with a List<?>
Pitfalls
Raw types disable checking entirely, arrays are covariant while generics are not, and the two combining produces heap pollution.
- What is a raw type and why does using one disable generics everywhere?
- What is heap pollution?
- Why is a generic varargs parameter unsafe?