Generics parameterize types: ArrayList<String> holds only strings at compile time. They eliminate casts and catch type errors before runtime—similar to TypeScript generics but enforced by the JVM via erasure.
Class and method generics
class Box<T> {
private T value;
void set(T value) { this.value = value; }
T get() { return value; }
}
Type erasure
Generic type parameters are erased at runtime—List<String> becomes raw List in bytecode. Do not rely on instanceof List<String>.
Important interview questions and answers
- Q: Why generics?
A: Type safety and clearer APIs without casting. - Q: What is erasure?
A: Compile-time feature; runtime sees raw types for backward compatibility.
Self-check
- What symbol declares a type parameter?
- Why avoid raw
ArrayListwithout type args?