SteelReed

Search

Search posts, questions…

3. Advanced Java

Java generics: type safety, wildcards, PECS and type erasure

Generics move type errors from runtime to compile time, but Java erases type arguments once it has checked them. Invariance, wildcards and the PECS rule, type erasure, raw types, type tokens like Jackson's TypeReference, and how to review generic signatures written by AI.

17 Nov 202610 min readMid

–

1. The problem

A reconciliation job reads 12,000 orders with objectMapper.readValue(json, List.class) and assigns them to a List<Order>. It compiles with one unchecked warning, and a test with an empty list passes. In production, orders.get(0).total() throws ClassCastException: LinkedHashMap cannot be cast to Order, three calls away from the parsing.

2. Key idea

The compiler checks types, then erases the type arguments from objects and inserts casts where values are read. Anything that slipped past compile time (raw types, unchecked casts, List.class) is checked by nobody at runtime. The error fires at get(), not at add().

When writing a signature, ask two questions. Does this parameter provide or receive data? Does the code need the type at runtime; if so, the type must be passed in as a value.

Tool Use when Don't use when
T on a method it links several places: input to output, two parameters of the same type T appears only once; a wildcard is simpler
? extends T the parameter is only read from (producer) you need add; return types
? super T the parameter only receives (consumer), comparators, callbacks you need to read exactly T back
List<?> element type doesn't matter: size, clear, printing you need to write
Type token (Class<T>, TypeReference) creating objects or arrays, deserializing JSON compile-time checks are enough

2.1 What does erasure forbid?

  • List<int>: primitives aren't Objects; use List<Integer> or IntStream.
  • new T(), new T[n]: nobody knows which class T is; pass a Supplier<T> or Class<T>.
  • obj instanceof List<String>: can't be told apart; use List<?>.
  • Overloads f(List<String>) and f(List<Integer>): same signature after erasure, a compile error.

Arrays go the other way: Integer[] is a Number[], so nums[0] = 3.14 compiles and throws ArrayStoreException at runtime. Generics chose invariance to stop this at compile time.

3. In Java

Four lines to remember: invariance, PECS, erasure, type tokens.

JAVA
List<Integer> ints = List.of(1, 2, 3);
// List<Number> nums = ints;            // compile error: generics are invariant
 
// PECS: src provides (extends), dest receives (super)
static <T> void copyInto(Collection<? super T> dest, Collection<? extends T> src) {
    for (T item : src) dest.add(item);
}
List<Number> numbers = new ArrayList<>();
copyInto(numbers, ints);                // T = Integer -> [1, 2, 3]
 
// Erasure: at runtime both lists share one class
new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass();   // true
 
// Need the type at runtime: pass it in as a value (mind the {})
List<Order> orders = objectMapper.readValue(json, new TypeReference<List<Order>>() {});

Other languages: C# keeps types at runtime (typeof(T)); Kotlin uses inline fun <reified T>; TypeScript erases every type and needs a runtime checker such as Zod.

Heap pollution and Collections.checkedList

Heap pollution is a List<String> variable pointing at an object that isn't really that type; the bug only shows later, in a compiler-inserted cast. Common sources: raw types and generic varargs (varargs are arrays, and a real T[] can't be created).

JAVA
List<String> strings = new ArrayList<>();
List raw = strings;          // allowed
raw.add(42);                 // only an unchecked warning, still runs
String s = strings.get(0);   // ClassCastException HERE, far from the bug

To find the bad write, wrap the list in Collections.checkedList(list, String.class). The wrong add throws immediately, and the stack trace points at the culprit. Put @SafeVarargs only on methods that neither write into nor return the varargs array.

4. Working with AI

Hand to AI: converting raw types to generics, writing PECS signatures, generating tests that call the API with List<Integer>, List<Number> and mixed lists.

Check in AI-written code:

  • Building with -Xlint:unchecked adds no new warnings; @SuppressWarnings("unchecked") has the smallest scope and a stated reason.
  • No raw types except class literals (List.class).
  • Read-only parameters are ? extends, write-only are ? super; return types have no wildcards.
  • Type tokens are concrete: no readValue(json, List.class), no TypeReference<List<T>>.
  • No class-level <T> used by only one method.

5. Exercises

Exercise 1: Review a readList helper

The AI says: "type-safe, uses TypeReference so the type isn't lost". Find the bug, name a test that proves it, fix it.

JAVA
static <T> List<T> readList(String json) throws IOException {
    return MAPPER.readValue(json, new TypeReference<List<T>>() {});
}
 
List<Order> orders = readList(body);
Order first = orders.get(0);
Solution to Exercise 1

The anonymous subclass records exactly List<T> in its .class, where T is a type variable, not Order. Every call uses the same anonymous class, so Jackson doesn't know T, treats it as Object, and returns a list of LinkedHashMap.

Test: assertInstanceOf(Order.class, readList(json).get(0)) fails. A test that only checks size() passes, which is how the bug slipped through.

Fix: take the type from the caller. static <T> List<T> readList(String json, Class<T> type) builds the type with MAPPER.getTypeFactory().constructCollectionType(List.class, type), or let callers pass a concrete TypeReference<List<Order>>.

Exercise 2: Read a revenue report incident

The nightly report failed 3 times this week, each time after the legacy CSV import job ran. Log: ClassCastException: class java.lang.String cannot be cast to class billing.Invoice at billing.ReportService.sumTotals(ReportService.java:41). Line 41 is for (Invoice inv : invoices), and nobody touched that file in 6 months. Last week LegacyCsvImporter.importInto(List rows) was merged. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: heap pollution. importInto(List rows) receives the List<Invoice> as a raw type and adds strings to it; the compiler only warns. The compiler-inserted cast in ReportService's for loop is the first to notice, so the stack trace points at the wrong place.
  • 15 minutes: wrap the list in Collections.checkedList(invoices, Invoice.class) before passing it to the importer: the bad add throws immediately, pointing at the importer. Pause the import job if the report must rerun.
  • Root fix: the signature importInto(Collection<? super Invoice> rows), parsing each CSV row into an Invoice. Add -Xlint:unchecked -Werror to the build.

Summary

  • List<Integer> is not a List<Number>; covariant arrays fail at runtime instead.
  • PECS: read ? extends, write ? super, both T.
  • Erasure removes type arguments from objects; casts fail where data is read, far from the bug.
  • Need the type at runtime: Class<T>, Supplier<T> or a TypeReference with a concrete type.
  • No raw types, no unchecked warnings without a reason.

Practice interview questions on this topic

All Java Core questions →

Loading comments…
Next on the roadmapLambdas and the Stream API: functional interfaces, lazy pipelines, Collectors and the traps