← Java roadmap

Topic 13 of 30 · Advanced

Generics

Type-safe reusable code, bounds and wildcards.

Concept

Generics let classes and methods work with any type while keeping compile-time type safety, so no casts are needed.

Bounded types restrict parameters: <T extends Comparable<T>>. Wildcards: ? extends T for reading (producer), ? super T for writing (consumer) — PECS.

Type erasure removes generic types at run time, so you can't create new T() or check instanceof List<String>.

Code (Java 21)

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

static <T extends Comparable<T>> T max(List<T> list) {
    T best = list.get(0);
    for (T x : list) if (x.compareTo(best) > 0) best = x;
    return best;
}

static double total(List<? extends Number> nums) {
    double s = 0;
    for (Number n : nums) s += n.doubleValue();
    return s;
}

Remember

  • PECS: Producer Extends, Consumer Super.
  • Generics work with objects only (use Integer, not int).
  • Erasure: generic info is gone at run time.

Interview questions

What is type erasure?

The compiler checks generic types, then replaces them with their bounds (or Object) in bytecode for backward compatibility.

List<Object> vs List<?>?

List<Object> accepts adding any object but isn't a supertype of List<String>. List<?> accepts any list type but you can't add (except null).

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Generics” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.