Lab 03: Advanced Generics

Objective

Master Java's generic type system: covariant ImmutableList<T> with map/filter, the PECS rule (? extends vs ? super), multiple bounds, generic records, CRTP builder pattern, and using ParameterizedType reflection to recover erased type arguments at runtime.

Background

Java generics use erasure — generic type parameters are removed at compile time. List<String> and List<Integer> are the same List at runtime. Understanding this explains why List<String> is not a subtype of List<Object> (invariance), why wildcards exist, and how type tokens work around erasure via anonymous class tricks.

Time

30 minutes

Prerequisites

  • Practitioner Labs 01–03

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: ImmutableList map/filter, PECS wildcards, bounded max, generic swap, Pair<A,B>, Comparable sort, type erasure, PECS summary

💡 PECS: "Producer Extends, Consumer Super." If a collection produces values you read (get()), use ? extends T. If it consumes values you write (add()), use ? super T. If you both read and write, use the concrete type T. This rule prevents ClassCastException at runtime while still allowing polymorphic usage.

📸 Verified Output:


Summary

Concept
Syntax
Rule

Upper bounded

? extends T

Read only (producer)

Lower bounded

? super T

Write only (consumer)

Unbounded

?

Read as Object only

Multiple bounds

T extends A & B

Must be class then interfaces

Type token

Anonymous subclass

Recovers erased type at runtime

Further Reading

Last updated