Kayavak / The Backend / BE·36 Generics and Type Parameters / Deeper
Deeper · The Backend
Generics and Type Parameters
The questions the chapter doesn't stop for: why this exists, the model to keep in your head, what changes when an assumption does, how sure we are of each claim, and what's still open. Read it after the chapter; back to the chapter.
Why does this exist?
Before Java 5 (2004), a List held Objects: you cast everything you took out, and a wrong type surfaced as a
ClassCastException far from where it went in. Generic types were well known from ML (1970s) and C++ templates, and
Martin Odersky and Philip Wadler showed how to add them to Java in the Pizza language (1997) and then GJ (1998),
which became Java 5's generics.
The decisive constraint was compatibility: millions of lines of existing code and libraries used raw collections, and
compiled classes had to keep working. So Java chose erasure: generic types are checked by the compiler and then
removed, leaving the old bytecode. C# made the opposite choice a year later (.NET 2.0, 2005), with generics kept at run
time, at the cost of breaking compatibility once. Most of Java generics' oddities (no new T(), no List<int>,
wildcards) follow from that one decision.
The mental model
Try it yourself first: write your own model in the Mental Model Explorer, then compare.
Generics let the compiler track what a container holds, so mistakes appear at compile time. In Java that knowledge
exists only at compile time: at run time a List<String> is just a List.
| Question | Answer |
|---|---|
| What is it? | Type parameters on classes, interfaces and methods, checked by the compiler |
| Problem it solves | Reusable code that's type-safe without casts |
| Parts | Type parameters and arguments, bounds, wildcards (? extends, ? super), inference, erasure |
| How it works | The compiler checks uses against the parameters, inserts casts, then erases the types |
| Assumptions | Every operation on generic values goes through code the compiler checked |
| When they change | Raw types, unchecked casts and arrays of generics let wrong values in (heap pollution), found later as ClassCastException |
| Where it fails | Run-time type questions (instanceof List<String>), primitives as type arguments |
| Related ideas | Static typing (Foundations, ch02); TypeScript's erased types (The Web Frontend, ch16) |
What if?
What if List<Dog> were a subtype of List<Animal>?
Reason it through, then open
See the derivation below: you could add a Cat through the List<Animal> reference and the list of dogs would hold
a cat. Java's arrays are covariant (Dog[] is an Animal[]) and pay for it with a run-time check that throws
ArrayStoreException. Generics chose to reject the program at compile time instead.
What if Java had reified generics, like C#?
Reason it through, then open
new T[], instanceof List<String> and overloading on List<String> vs List<Integer> would work, and
List<int> could store numbers without boxing. The price would have been breaking every library compiled before
generics, in 2004. Valhalla is trying to get some of the benefits (specialisation over value types) without that break.
Where the boundary is
| Aspect | ? extends T |
? super T |
|---|---|---|
| You can | Read values as T |
Write values of T |
| You can't | Write (except null) | Read as anything but Object |
| Example | copy(List<? extends Number> src, …) |
…, List<? super Integer> dst) |
| Memory aid | Producer extends | Consumer super (PECS) |
Derive it
Why generic types must be invariant if they're mutable.
- Suppose
List<Dog>were a subtype ofList<Animal>. - Then
List<Animal> animals = dogs;would compile, wheredogsis aList<Dog>. animals.add(new Cat())type-checks: aCatis anAnimal.- But
animalsanddogsare the same list, soDog d = dogs.get(0)now returns aCat: the type system has been broken. - So a mutable container can only be covariant (step 2) if it's read-only, and only contravariant if it's write-only.
Java makes generics invariant and lets each use choose with wildcards; Kotlin and C# let declarations choose
(
out T,in T).
How sure are we?
| Claim | How it's known | Where from |
|---|---|---|
| Covariant mutable containers are unsound | Theorem | The argument above |
| Java generics came from GJ (Odersky, Wadler and others) | Historical | GJ paper, 1998; Java 5, 2004 |
| Erasure was chosen for migration compatibility | Historical | JSR 14 and the designers' accounts |
Still open
Specialised generics over value classes is one of Valhalla's hardest parts; its design is still evolving.
What would change your mind? If a language had covariant mutable arrays with no run-time checks and no type
errors in practice, the derivation would be wrong. Java's own ArrayStoreException shows the check is needed.
Recall
Why isn't `List<Dog>` a `List<Animal>`?
Then you could add a Cat through the Animal view and break the Dog list's type.
What does PECS stand for?
Producer extends, consumer super: read with ? extends, write with ? super.
Why does Java erase generic types?
For compatibility with code and libraries compiled before generics existed.
Why are Java arrays different from generics?
Arrays are covariant and check stores at run time (ArrayStoreException); generics are invariant and checked at compile time.
Reflect
Be honest with yourself; this stays in your browser. Anything you can't tick yet is what to revisit.