Java Materials
← Core Java · Chapter 5

Generics and the type system

Generics shift checks to compile time. A type parameter can express a dependency between multiple arguments and the return type. Use bounded type parameters only when implementation or callers need that bound. A generic method is often clearer than a generic class when the relationship belongs to one operation.

PECS and independent read/write contracts

Definition:

PECS expresses whether a generic argument produces values, consumes values, or needs both operations.

Explanation:

Invariance protects mutable containers.

Illustration image:

PECS and independent read/write contracts. List<Integer> source · Read as Integer · Append Integer · List<Number> targetPECS and independent read/write contractsSource or actorList<Integer> sourceFirst boundaryRead as IntegerInspected stateAppend IntegerObservable effectList<Number> target
List<Integer> source · Read as Integer · Append Integer · List<Number> target

Example:

Worked Java example · see surrounding context in notes
static <T> void appendAll(java.util.List<? extends T> src,
                          java.util.List<? super T> dst) {
    for (T item : src) dst.add(item);
}

Expected behavior. A List<Integer> source can append into a List<Number> target.

Internal working:

A source typed ? extends T is safe to read as T; a target typed ? super T is safe to write T into. A wildcard capture helper can maintain a single unknown type where reading and writing the same list is allowed. Keep the bound in the signature only when it expresses a needed constraint.

Interview questions:

Why can a destination List<Number> consume Integer values but not replace List<Integer>?

It can accept Integers, but also accepts other Number subtypes. Mutable generic types are invariant.

Erasure, bridge methods and raw boundaries

Definition:

Type erasure maps many generic types to runtime bounds; a bridge can preserve overriding after that mapping.

Explanation:

Erasure maps parameterized types to bounds in most runtime operations.

Illustration image:

Erasure, bridge methods and raw boundaries. Mapper<T>.map · Erased map(Object) · Bridge casts to String · Trim.map(String)Erasure, bridge methods and raw boundariesSource or actorMapper<T>.mapFirst boundaryErased map(Object)Inspected stateBridge casts to StringObservable effectTrim.map(String)
Mapper<T>.map · Erased map(Object) · Bridge casts to String · Trim.map(String)

Example:

Worked Java example · see surrounding context in notes
interface Mapper<T> { T map(T value); }
class Trim implements Mapper<String> {
    public String map(String value) { return value.trim(); }
}
// javap -c -p Trim

Expected behavior. javap shows the typed method and an erased bridge that checks and delegates.

Internal working:

The compiler may emit a bridge to preserve overriding after erasure. Raw types and unchecked casts suppress compile-time guarantees and can surface as distant ClassCastException failures. When integrating legacy data, validate elements at the boundary instead of casting a whole List.

Interview questions:

Why does javap show two map methods in Trim?

The synthetic bridge exposes the erased signature and casts before delegating to the typed implementation.

Generic arrays and safe varargs

Definition:

Heap pollution occurs when a parameterized reference points to data inconsistent with its declared type.

Explanation:

Arrays retain runtime component type, while generic element arguments are usually erased.

Illustration image:

Generic arrays and safe varargs. Generic varargs · Erased array · Unsafe alias may write · Later read may failGeneric arrays and safe varargsSource or actorGeneric varargsFirst boundaryErased arrayInspected stateUnsafe alias may writeObservable effectLater read may fail
Generic varargs · Erased array · Unsafe alias may write · Later read may fail

Example:

Worked Java example · see surrounding context in notes
@SafeVarargs
static <T> java.util.List<T> concatenate(java.util.List<? extends T>... sources) {
    var out = new java.util.ArrayList<T>();
    for (var source : sources) out.addAll(source);
    return out;
}

Expected behavior. The method only reads the varargs array and returns a separate list; input lists themselves need no mutation.

Internal working:

Java prohibits new List<String>[n]. Generic varargs receive an array whose generic component is not reifiable; never expose it through an unsafe alias or write incompatible values. @SafeVarargs asserts that the implementation obeys that discipline.

Interview questions:

What does @SafeVarargs promise?

The implementation does not perform unsafe operations on its generic varargs array; it does not validate element types at runtime.

Reference subtopics

Invariance, PECS and capture

List<Integer> is not List<Number> because the latter would permit adding a Double. A List<? extends T> produces T values, while List<? super T> can consume T. Capture helpers give a name to an unknown wildcard when operations must preserve the same element type. Intersection bounds express several required capabilities.

Inference and erasure

The diamond operator derives type arguments from context. Erasure uses runtime bounds and compiler-inserted casts. A bridge method can preserve polymorphism after erasure. Raw types bypass checks and can hide a bad insertion until a distant read. Avoid unchecked casts unless an explicit runtime invariant justifies them.

Arrays, varargs and heap pollution

Arrays carry a runtime component type; most generic type arguments are erased. This is why construction such as new List<String>[n] fails. Generic varargs create an array and can expose heap pollution if written through an unsafe alias or returned. @SafeVarargs is a promise about implementation behavior, not a runtime check.

Run the complete Java labs ↗ · Java reference ↗