Java ยท Chapter 37 of 42

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.

Syntax
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.

Example 1 (java)
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());
  }
}
Output
Hello

Box<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).
๐Ÿ’ก Note: Generics are erased at runtime (type erasure), so you can't check generic types with instanceof at runtime.

๐Ÿ“ Quick Quiz

1. What does Box<String> mean for a generic class Box<T>?

2. What problem do generics solve?

3. What is a common generic letter used for 'key'?