Java Generics
Generics let you write classes, interfaces, and methods that work with any type while maintaining compile-time type safety, using angle-bracket syntax like `List<String>`.
Without generics, collections stored plain Objects, requiring manual casting and risking runtime ClassCastException; generics catch such type errors at compile time instead.
class Box<T> {
T value;
}
Box<String> b = new Box<>();Generic classes and methods
A generic class like `class Box<T>` can hold any type T, decided when the class is instantiated, e.g. `Box<String>`.
Why generics matter
Generics eliminate the need for manual casting and catch type mismatches at compile time rather than at runtime.
class Box<T> {
private T value;
void set(T value) { this.value = value; }
T get() { return value; }
}
public class Main {
public static void main(String[] args) {
Box<String> box = new Box<>();
box.set("Hello");
System.out.println(box.get());
}
}HelloBox<T> is a generic class; here T is bound to String when the Box is created.
Key points
- Generics enable compile-time type safety for classes/methods.
- <T> is a placeholder type parameter, replaced with a real type on use.
- Generics remove the need for manual casting.
- Common generic type letters: T (type), E (element), K/V (key/value).
