Boxes with labels
Ana packs fruit into boxes in a packing hall. Ben, downstairs, takes things out and sells them as apples.
In the old days the boxes were plain. Ana could drop a pear into a box by mistake and nobody would notice. Ben only finds out when he bites into his "apple". By then the mistake is far away, and it's hard to tell who made it.
Now every box can carry a label, like "apples only". A checker stands at the hall door and looks at everything Ana packs. A pear headed for the apples box is stopped right there, before it goes anywhere. And because the label is trusted, Ben no longer has to inspect each item: if it came out of an apples box, it's an apple.
Labels like this are called generics.
Why generics
Before Java 5, collections held Object. You cast on the way out, and a wrong element only failed when it was read:
1List names = new ArrayList(); // raw type2names.add("Ana");3names.add(42); // compiles: anything is an Object4String s = (String) names.get(1); // ClassCastException, far from the bug
Generics add type parameters to classes, interfaces and methods, so the compiler knows the element type:
1List<String> names = new ArrayList<>(); // diamond infers <String>2names.add("Ana");3names.add(42); // compile error4String s = names.get(0); // no cast needed
Two wins: type errors move from run time to compile time, and the casts disappear from your code (the compiler still
inserts them in the bytecode, as we'll see). Generics only accept reference types, so List<int> is illegal; use
List<Integer> and autoboxing.
A box design with a blank
The box factory doesn't build a separate design for every fruit. It has one design with a blank on the label: "_____ only". When you order a box, you fill in the blank: an apples box, a bricks box, whatever you need.
Helpers can work the same way. Cleo's job card says "pick the ripest item from any box", and whatever box she's handed, she hands back that kind of thing: apples from an apples box.
But Cleo can only judge ripeness on fruit, so her card says "fruit boxes only". That limit is called a bound. Hand her a box of bricks and the checker stops it at the door.
Generic classes, methods and bounds
A generic class declares type parameters; each use supplies type arguments:
1public class Box<T> {2private T item;3public void put(T item) { this.item = item; }4public T get() { return item; }5}67Box<Apple> apples = new Box<>();8Box<Brick> bricks = new Box<>();
A generic method declares its own type parameter before the return type, and the compiler infers it at each call:
1static <T> T first(List<T> list) { return list.get(0); }23Apple a = first(appleList); // T inferred as Apple
A bounded type parameter restricts the type arguments and lets the body call the bound's methods:
1static <T extends Fruit> T ripest(List<T> fruit) {2T best = fruit.get(0);3for (T f : fruit) if (f.ripeness() > best.ripeness()) best = f;4return best;5}67ripest(appleList); // returns Apple8ripest(brickList); // compile error: Brick is not a Fruit
extends covers interfaces too, and you can combine bounds: <T extends Number & Comparable<T>> (a class first, then
interfaces). The classic recursive bound is <T extends Comparable<? super T>>, as in Collections.sort.
An apples box isn't a fruit box
Every apple is a fruit. So is a box of apples a box of fruit? It sounds right, but no.
If the checker let Ben call the apples box "a fruit box", he could then drop a pear in, because pears are fruit too. The apples box would quietly hold a pear. So the checker refuses: an apples box is an apples box, full stop. This strictness is called being invariant.
Old wooden crates work differently. Their label is burnt into the wood, so they're allowed to be called fruit crates. But the crate itself checks every item put in, downstairs, while the work is already going on. Drop a pear into an apple crate and it's refused at that moment, not at the door.
Invariance vs covariant arrays
Generic types are invariant: List<Integer> is not a subtype of List<Number>, even though Integer is a
subtype of Number. If it were, this would compile and corrupt the list:
1List<Integer> ints = new ArrayList<>();2List<Number> nums = ints; // compile error, and this is why:3nums.add(3.14); // a Double inside a List<Integer>
Arrays are covariant: Integer[] is a subtype of Number[]. Arrays know their component type at run time, so the
JVM checks every store instead:
1Number[] nums = new Integer[2]; // compiles2nums[0] = 3.14; // ArrayStoreException at run time
Same mistake, different moment: generics reject it at compile time, arrays at run time. That's one reason to prefer
List<E> to E[] in APIs.
Take-out boxes and put-in boxes
Sometimes Cleo doesn't care exactly which box she gets. Her new job is to move fruit from one box into another.
For the box she takes from, any box of "some kind of fruit" will do: apples, pears, a mix. Whatever she pulls out is certainly a fruit. But she mustn't put anything into it: it might be the apples box, and her pear would be wrong.
For the box she puts into, any box that accepts fruit will do: a fruit box, or even an "anything" box. She can safely put fruit in. But if she takes something out, all she knows is that it's "a thing".
These "some kind of" labels are called wildcards. The rule of thumb: a box you take from is labelled "some kind of fruit"; a box you put into is labelled "fruit or anything bigger".
Wildcards and PECS
Invariance makes APIs rigid, so Java has wildcards:
| Type | Accepts | You can read | You can write |
|---|---|---|---|
List<? extends Fruit> | List<Fruit>, List<Apple>, โฆ | Fruit | nothing but null |
List<? super Apple> | List<Apple>, List<Fruit>, List<Object> | only Object | Apple and its subtypes |
List<?> | any list | only Object | nothing but null |
Joshua Bloch's mnemonic is PECS: producer extends, consumer super. A parameter you read from produces values, so
use ? extends T; a parameter you write to consumes values, so use ? super T. The JDK does exactly this:
1// java.util.Collections2public static <T> void copy(List<? super T> dest, List<? extends T> src)34static void pour(List<? extends Fruit> from, List<? super Fruit> to) {5for (Fruit f : from) to.add(f);6}7pour(appleList, objectList); // fine
Use wildcards in parameters, not in return types: a returned List<? extends Fruit> forces every caller to deal with
the wildcard. If you need to read and write the same element type, use a plain type parameter.
Labels peeled at the gate
Here's the surprise. The labels only exist in the packing hall. When boxes leave through the factory gate, the labels are peeled off, and downstairs every crate is just a plain box. This is called type erasure.
It still works, because the checker already made sure every box was packed right. The checker also leaves a small note at each spot where Ben takes things out: "check this is an apple". Ben's job never changes, and nobody had to rebuild the old plain-box shipping yard.
But downstairs, nobody can read a label any more. "Is this an apples crate?" can't be answered. "Make me a new one of whatever goes in this crate" can't be done either. If Ana needs that, she has to send along a label card herself: a little card saying "apple" that travels with the crate.
Type erasure
Java implements generics by erasure: the compiler checks types, then removes type arguments from the bytecode.
Each type parameter becomes its leftmost bound (Object if unbounded, Fruit for T extends Fruit), and the compiler
inserts casts where a value of type T is used. new ArrayList<String>() and new ArrayList<Integer>()
share one runtime class, ArrayList.class. This kept bytecode compatible with pre-generics code and libraries.
Erasure explains the restrictions:
1class Box<T> {2T make() { return new T(); } // error: T is unknown at run time3T[] many() { return new T[10]; } // error: no generic array creation4static T shared; // error: one static field for every Box<X>5}6Object obj = apples;7if (obj instanceof List<String>) ... // error: Object can't be safely checked as List<String>8if (obj instanceof List<?>) ... // fine9void f(List<String> a) {} void f(List<Integer> b) {} // error: same erasure
Types that survive erasure intact are reifiable: primitives, non-generic types, raw types, unbounded wildcards
like List<?>, and arrays of any of these. Since Java 16, instanceof with a parameterized type is allowed when the
compiler can prove it safe (Collection<Apple> c; c instanceof List<Apple>).
When you need the type at run time, pass it explicitly:
1<T> T create(Class<T> type) throws ReflectiveOperationException {2return type.getDeclaredConstructor().newInstance();3}4Apple a = create(Apple.class);
Class<T> can't express List<Apple> (there's no List<Apple>.class). For that, frameworks use a super type
token: the type arguments in a class's supertype declaration are kept in the class file and readable by
reflection, so an anonymous subclass captures them. Spring's ParameterizedTypeReference and Jackson's TypeReference
work this way:
1List<Apple> apples = restClient.get().uri(url).retrieve()2.body(new ParameterizedTypeReference<List<Apple>>() {});
Bridge methods
Erasure can break overriding, so the compiler adds synthetic bridge methods:
1class Node<T> { void setData(T data) { ... } } // erases to setData(Object)2class IntNode extends Node<Integer> {3@Override void setData(Integer data) { ... } // overrides in Java, but its erasure setData(Integer) doesn't match setData(Object) in the bytecode4}5// javac generates in IntNode:6// void setData(Object data) { setData((Integer) data); }
Polymorphism keeps working, and a caller that slips a String in through a raw Node gets a ClassCastException
from the bridge's cast. Bridges show up in stack traces and in reflection (Method.isBridge()). Signatures and
declared generic types are kept in the class file's Signature attribute, which is why reflection can still report
List<String> for a field or method parameter, even though the object itself doesn't know.
Sneaking past the checker
The checker only helps if boxes go through the door with their labels. Bob still has old habits: he treats the apples box as a plain box. The checker can't tell what he's putting in, so all it can do is warn him.
Bob drops a pear in. Now the apples box holds a pear, and nothing notices. This is called heap pollution. Much later, Ben pulls out the pear expecting an apple, and things go wrong, far from Bob.
Some job cards take a whole bundle of boxes at once. Bundles are wrapped in a plain sack, so the checker always warns that something could sneak in. If Cleo only ever reads from the bundle and never puts anything into the sack, she can sign a promise saying so, and the checker stops warning.
Raw types, heap pollution and @SafeVarargs
A raw type is a generic type used without type arguments (List instead of List<String>). It exists for
compatibility with pre-generics code, turns off type checking, and the compiler only warns:
1List<Apple> apples = new ArrayList<>();2List raw = apples; // allowed3raw.add(new Pear()); // unchecked warning, compiles4Apple a = apples.get(0); // ClassCastException here, at the inserted cast
Heap pollution is a variable of a parameterized type referring to an object that isn't of that type. It comes from
raw types, unchecked casts like (List<Apple>) obj, and generic varargs. Because of erasure nothing fails at the point
of corruption, only later at an inserted cast. Treat every unchecked warning as a possible bug; suppress one with
@SuppressWarnings("unchecked") on the smallest scope, only once you've proved it safe.
Generic varargs (T..., List<String>...) are backed by an array whose component type is erased, so the compiler
warns "possible heap pollution" at the declaration. If the method only reads the elements and never stores into the
array or lets it escape, annotate it with @SafeVarargs, as List.of(E...) and Arrays.asList do. It's allowed only
on methods that can't be overridden: static, final and (since Java 9) private methods, and constructors.
1@SafeVarargs2static <T> List<T> listOf(T... items) { return List.copyOf(Arrays.asList(items)); }