Skip to content

Chapter 20 of 37

Generics

Write reusable type-safe APIs with bounds, wildcards, PECS, and type erasure.

42 minutes 10 quick checksBy Subha Prasad
Lesson 20 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Generics move type mistakes from runtime to compilation. Type parameters appear on classes, interfaces, and methods; bounds state required capabilities.

Bounds and variance

static double total(List<? extends Number> values) {
    double sum = 0;
    for (Number value : values) sum += value.doubleValue();
    return sum;
}

static void addDefaults(List<? super Integer> target) {
    target.add(0);
}

Generic types are invariant: List<Integer> is not List<Number>. Follow PECS—producer extends, consumer super. Java implements most generics through type erasure, so type arguments are usually unavailable at runtime, primitives cannot be direct arguments, and creating new T() or new T[] is restricted. Avoid raw types and unchecked casts; prefer bounded APIs that express the operations truly needed.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes type parameter?
Which Java term matches this description: A named placeholder type declared by a generic class or method.
Which statement best describes bounded wildcard?
Which Java term matches this description: A use-site type such as ? extends Number or ? super Integer.
Which statement best describes type erasure?
Which Java term matches this description: Translation that removes most generic type arguments from runtime representation.
Which statement best describes invariance?
Which Java term matches this description: The rule that List<Integer> is not a subtype of List<Number>.
Which statement best describes PECS?
Which Java term matches this description: The guideline: producer extends, consumer super.

0 of 10 checks passed

Your progress is saved on this device.

Generics | Java Lesson | Subha Prasad