All topics
library
intermediate

Generics Fundamentals

Understand type parameters, type safety at compile time, and why generics exist.

Generics enable type-safe code by letting you parameterize classes, interfaces, and methods with type parameters. Before generics (pre-Java 5), collections stored Object and every retrieval required a cast — ClassCastException at runtime was common.

Generics = labeled containers. A box labeled 'Books Only' (Box<Book>) prevents you from putting shoes in at compile time — no need to check every item when you take it out.

Key Concepts

1
With generics, the compiler enforces type safety: List<String> only accepts Strings, and get() returns String without casting. Type errors are caught at compile time, not runtime.
2
Generic class: class Box<T> { private T value; }. T is a type parameter — a placeholder that's replaced by an actual type when the class is used: Box<String>, Box<Integer>.
3
Generic method: <T> T identity(T value) { return value; }. The type parameter is declared before the return type and inferred from arguments.
4
Generic interface: interface Comparable<T> { int compareTo(T o); }. Classes implement it with a specific type: class Age implements Comparable<Age>.
5
Conventions: T (Type), E (Element), K (Key), V (Value), N (Number), S/U/V for additional types.
6
Limitations: no primitive type parameters (use wrapper), no new T() (type erasure), no instanceof T (type erasure), no static fields of type T.