4 · Data & Collections · lesson 22 of 41
Generics
Type parameters for reusable, type-safe containers.
Java
class Box<T> {
private T value;
public void set(T v) { value = v; }
public T get() { return value; }
}
Box<Integer> b = new Box<>();
b.set(42);
// Bounded type parameter
static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
List<? extends Number> readOnly; // upper-bounded wildcardKey takeaways
- ✓Generics are erased at runtime — type checks happen at compile time.
- ✓Use bounds (T extends X) to constrain what T can be.