Skip to content
UPEEC

Generics in Java

Type parameters make classes and methods work with any type while staying type-safe.

Intermediate
Comments 0
class Box<T> {
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}

static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) >= 0 ? a : b;
}

Generics catch type errors at compile time. Java implements them by type erasure — the type information is removed at run time, so you can't write new T().

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.