Generics and Type Erasure

Type parameters sit inside every collection.

6 lessons · 23 past questions · 130 marks in the papers collected here

Open the interactive lessons →Generics and Type Erasure past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. A type you choose later
  2. What is left at run time
  3. Two methods, one signature
  4. Arrays bend, lists do not
  5. Saying "some type"
  6. Containers and their limits

1. A type you choose later

A placeholder for a type, filled in by whoever uses the code.

how a letter such as T is declared, where it can be used, and how to limit it

You need a parcel that can carry any one thing. A first idea is a field of type Object, because every object fits in it. Read this program and decide where it fails.

The Object parcel

class OldParcel {
    private Object item;
    void put(Object x) { item = x; }
    Object take() { return item; }
}
public class Main {
    public static void main(String[] args) {
        OldParcel p = new OldParcel();
        p.put("socks");
        p.put(42);
        System.out.println("packed");
        String s = (String) p.take();
        System.out.println(s);
    }
}

The mistake was made on one line and noticed on another, and only while the program ran. Think of a box with a label on the lid. If the label says "socks", whoever fills it is stopped at the door. The analogy stops here: the Java label is read by the compiler, not by the running program.

Why a placeholder works. The class cannot know today what you will store tomorrow. So it writes a name, T, for "the type you will pick". When you pick String, the compiler checks every put and every take against String.

Declaring a type variable

class Parcel<T> declares T for the whole class. static <E> E pick(E x) declares E for that one method. The brackets after the class name, or before the return type, are the declaration.

Worked example: A parcel with a label

Problem.

What does this program print?

class Parcel<T> {
    private T item;
    void put(T x) { item = x; }
    T take() { return item; }
}
public class Main {
    public static void main(String[] args) {
        Parcel<String> p = new Parcel<>();
        p.put("socks");
        String s = p.take();
        System.out.println(s.toUpperCase());
    }
}

What is asked.

The printed line.

Idea.

Replace T by String in your head and read the class again.

  1. new Parcel<>() takes its type argument from the left side, so T is String here.
  2. put("socks") accepts a String.
  3. take() returns a String, so no cast is written and toUpperCase() is allowed.

Answer.

SOCKS

Common mistake.

Writing a cast before toUpperCase(). The compiler already knows the type.

What if

Parcel<String> stores socks and prints SOCKS.

  • Add p.put(42); after the first put. Does it compile?
    It does not compile.. put now expects a String, so the wrong value is caught on its own line.
  • Use Parcel<Integer>, call put(42) and print p.take() + 1. What prints?
    It prints 43.. take() returns an Integer, which unboxes for the addition.
  • Write Parcel<int> instead of Parcel<Integer>. Does it compile?
    It does not compile.. A type argument must be a reference type. Primitive types such as int are not allowed.

Worked example: A method with its own letter

Problem.

lastOf works on two different arrays. What are the two lines?

public class Main {
    static <T> T lastOf(T[] row) {
        return row[row.length - 1];
    }
    public static void main(String[] args) {
        String[] pets = {"cat", "eel"};
        Integer[] rolls = {4, 9, 6};
        System.out.println(lastOf(pets).length());
        System.out.println(lastOf(rolls) + 1);
    }
}

What is asked.

Both printed lines.

Idea.

The compiler chooses T freshly for each call, from the argument.

  1. For lastOf(pets) the argument is a String[], so T is String and the result has length().
  2. The last pet is eel, whose length is 3.
  3. For lastOf(rolls) the argument is an Integer[], so T is Integer.
  4. The last roll is 6, and adding 1 gives 7.

Answer.

3, then 7

Common mistake.

Thinking T stays String after the first call.

Choosing T from the arguments is called type inference. You do not write the type argument at the call.

Who can see which letter? A class's letter belongs to each object, because each object was built with its own type argument. A static member belongs to the class itself and is shared by all of them, so it has no single T to use.

Where a letter is visible

DeclaredVisible inNot visible in
class Shelf<T>instance fields, constructors, instance methodsstatic fields and static methods
<U> String label(U tag)that method onlyevery other method
static <V> V same(V v)that method onlyevery other method

Three letters, three scopes

class Shelf<T> {
    T top;
    <U> String label(U tag) {
        return tag + ":" + top;
    }
    static <V> V same(V v) {
        return v;
    }
}
public class Main {
    public static void main(String[] args) {
        Shelf<Integer> s = new Shelf<>();
        s.top = 5;
        System.out.println(s.label("row"));
        System.out.println(Shelf.same("ok"));
    }
}
What if

Shelf has the class letter T, a method letter U and a static method with its own V.

  • Add the field static T spare; to Shelf. Compile or not?
    It does not compile.. A static field is shared by every kind of shelf, so it cannot have the object's T.
  • Add static void drop(T x) { } to Shelf. Compile or not?
    It does not compile.. A static method cannot use the class's letter.
  • Add static <T> void drop(T x) { } to Shelf. Compile or not?
    It compiles.. The method declares a new T of its own. It only shares the spelling with the class's letter.

Now a new need. total should add the weights of two things. With a plain T, the compiler knows nothing about the value except that it is an Object. You may call only the methods of Object. A bound buys you more: <T extends Weighable> promises that every T is Weighable.

Worked example: A bound unlocks a method

Problem.

What prints, and why may total call grams()?

interface Weighable {
    int grams();
}
class Loaf implements Weighable {
    public int grams() { return 400; }
}
public class Main {
    static <T extends Weighable> int total(T a, T b) {
        return a.grams() + b.grams();
    }
    public static void main(String[] args) {
        System.out.println(total(new Loaf(), new Loaf()));
    }
}

What is asked.

The printed line and the reason.

Idea.

The bound tells the compiler which methods every T has.

  1. The header says <T extends Weighable>, so a and b are at least Weighable.
  2. Weighable declares grams(), so both calls are legal.
  3. Each loaf returns 400, and the sum is 800.

Answer.

800

Common mistake.

Writing implements in the bound. A bound always uses extends, also for an interface.

Bound or no bound

Bounded

grams() is allowed.

static <T extends Weighable> int one(T a) {
    return a.grams();
}

Unbounded

grams() is rejected.

static <T> int one(T a) {
    return a.grams();
}

The difference. The words extends Weighable.

Without a bound, a type variable offers only the methods of Object.

When this breaks

"The brackets declare a letter" fails when you write the letter only in the parameter list, as in static void f(T x). Nothing declares T, so the compiler searches for a class called T and reports that it cannot find the symbol.

2. What is left at run time

After checking, the compiler removes the type placeholders.

how the compiler rewrites generic code into ordinary code

You make a list of words and a list of counts. The compiler treats them as different types and stops you from mixing them. Does the running program also see two different classes?

Two lists, one class

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        System.out.println(words.getClass() == counts.getClass());
        System.out.println(words.getClass().getSimpleName());
    }
}

Think of stage directions in a play script. The director reads them to check every move, but the audience hears only the lines. The compiler reads your type arguments, checks every move, and leaves them out of what runs. The analogy stops at one point: Java keeps the bound as a real type in the result.

Why remove them? Java added generics after a large amount of code already existed. Removing the extra information lets new and old code share the same classes. The price is that the running program cannot ask what T was. This removal is called erasure.

The replacement rules

You wroteErased formReason
T with no boundObjectanything may be stored
T extends BBevery T is at least a B
T extends B & CBthe first bound is used
List<T>Listbrackets and their content go
T[]the erased type of T, then []an array stays an array
int, Stringunchangednothing generic in them

Jar before erasure

import java.util.*;
class Jar<T extends Number> {
    private T value;
    T get() { return value; }
    void set(T v) { value = v; }
    static <E> E first(List<E> items) { return items.get(0); }
    static <C extends Comparable<C>> C larger(C a, C b) {
        return a.compareTo(b) >= 0 ? a : b;
    }
}

Erase one class, line by line

  1. The class header loses <T extends Number>. Remember the bound: every T inside will become it.
  2. Field and method use the class's T, so both now say Number, not Object.
  3. E is the method's own variable with no bound: E becomes Object. List<E> becomes plain List.
  4. A bound that is itself generic, Comparable<C>, also loses its brackets.

Worked example: Erase a tray

Problem.

Write the field and the three methods of Tray as they look after erasure.

class Tray<T> {
    private T cup;
    T peek() { return cup; }
    <E extends CharSequence> int width(E text) {
        return text.length();
    }
    void fill(T[] cups) { cup = cups[0]; }
}

What is asked.

Four erased declarations.

Idea.

Take each letter, find its bound, and substitute.

  1. T belongs to the class and has no bound, so cup and peek() use Object.
  2. E belongs to width and has the bound CharSequence, so the parameter becomes CharSequence.
  3. The return type int is not generic and stays.
  4. T[] cups is an array of T, so it becomes Object[].

Answer.

Object cup; Object peek() int width(CharSequence text) void fill(Object[] cups)

Common mistake.

Writing Object width(...). A return type that was never a letter does not change.

What if

Tray<T> erases to Object cup, Object peek(), int width(CharSequence) and void fill(Object[]).

  • The class header becomes class Tray<T extends Number>. Which declarations change?
    The field cup becomes Number, peek() returns Number and fill takes Number[]; width is unchanged.. Only the class's T got a bound. E has its own.
  • A parameter T[][] grid is added to fill. What is its erased type with the original header?
    It becomes Object[][].. Each pair of brackets stays; only the letter is replaced.

Worked example: Two bounds and a map

Problem.

Erase peak, order and lookup.

import java.util.*;
class Ledger {
    <T extends Number & Comparable<T>> T peak(List<T> xs) {
        return xs.get(0);
    }
    <T extends Comparable<T>> void order(T[] xs) { }
    <K, V extends Number> V lookup(Map<K, V> m, K key) {
        return m.get(key);
    }
}

What is asked.

Three erased headers.

Idea.

Replace letters by first bounds, then drop every pair of angle brackets that follows a type name.

  1. In peak, the first bound of T is Number, so it returns Number, and List<T> becomes List.
  2. In order, the bound is Comparable<T>; its brackets go too, so the parameter is Comparable[].
  3. In lookup, K has no bound and becomes Object.
  4. V becomes Number, and Map<K, V> becomes Map.

Answer.

Number peak(List xs) void order(Comparable[] xs) Number lookup(Map m, Object key)

Common mistake.

Writing List<Number> xs. Nothing is left between angle brackets.

Checking the result. The JDK tool javap -s prints the descriptor of each compiled method: the parameter types inside round brackets, then the return type. For Number peak(List xs) it prints (Ljava/util/List;)Ljava/lang/Number;. Read it as: takes a List, returns a Number.

Reading a descriptor

SymbolMeaning
Ljava/lang/Object;the class between L and ;
[an array of what follows
Iint
Ddouble
Zboolean
Vvoid, no result
Notice

For Tray, the method fill is listed as ([Ljava/lang/Object;)V and width as (Ljava/lang/CharSequence;)I.

A lone letter or a letter in brackets

Lone letter

The parameter turns into the bound.

<T extends Number> void put(T x)
// erased: void put(Number x)

Letter in brackets

The brackets vanish and the bound is not written there.

<T extends Number> void put(List<T> x)
// erased: void put(List x)

The difference. T against List<T>.

A lone letter is replaced; a letter inside brackets disappears with the brackets.

Notice

Some exam choices write List<Number> or List<Object> for an erased parameter. The compiled signature is the plain List. When no choice says so, pick the one whose other types are all right and whose bracket content matches the bound, and know that it is only the closest.

When this breaks

"The compiler checked it, so it is safe" fails when a raw type is used. A raw type switches the check off, a wrong value slips in, and the failure appears later at an innocent-looking line.

A raw list lets the wrong thing in

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        List raw = names;
        raw.add(7);
        System.out.println(names.size());
        String first = names.get(0);
        System.out.println(first);
    }
}

3. Two methods, one signature

Erase first, then ask whether the class has the same method twice.

when two generic declarations are rejected as the same method

A Bell wants one ring for text-like things and another for everything else. Both take "some letter". Will Java accept two methods that both look like ring(T x)?

Think of two forms in an office that have different headings, but the clerk files them by the boxes to be filled. If the boxes are the same, the clerk cannot keep both. The analogy stops here: the clerk is the compiler, and it files by the erased types.

Why judge after erasure? Java tells the methods of one class apart by name and parameter types. After erasure, only the erased parameter types are left in the method's signature. Two methods that match there cannot be kept apart, so the compiler refuses them.

The clash test
  1. Erase each parameter type. 2. Compare method names and erased parameter lists. 3. If both are equal within one class, the declaration is rejected. Return types and letter names are not compared.

Worked example: Different bounds, two methods

Problem.

What does this print?

class Bell {
    <T extends CharSequence> void ring(T x) {
        System.out.println("chars " + x.length());
    }
    <T> void ring(T x) {
        System.out.println("any " + x);
    }
}
public class Main {
    public static void main(String[] args) {
        Bell b = new Bell();
        b.ring("dong");
        b.ring(8);
    }
}

What is asked.

Two lines.

Idea.

Erase both methods, then pick the most specific one that accepts the argument.

  1. The first erases to ring(CharSequence), the second to ring(Object). No clash.
  2. ring("dong"): a String fits both, and CharSequence is the more specific, so it prints chars 4.
  3. ring(8): an Integer is not a CharSequence, so only the second fits and prints any 8.

Answer.

chars 4, then any 8

Common mistake.

Calling it a duplicate because both are written ring(T x).

What if

Bell has <T extends CharSequence> ring(T) and <T> ring(T) and compiles.

  • The first header becomes <T extends Object> void ring(T x) and its body prints x only. Compile or not?
    It does not compile.. T extends Object erases to Object, the same as the second method.
  • Add <U> void ring(U y) { }. Compile or not?
    It does not compile.. U with no bound erases to Object, which is already taken.
  • Add void ring(String s) { }. Compile or not?
    It compiles.. Its erased parameter is String, which no other ring has.

Two names, one erased signature

  1. The first ring erases to ring(CharSequence).
  2. The second erases to ring(Object). The parameter types differ, so the two can live together.
  3. A third one with U erases to ring(Object) too. A new letter is not a new signature.
  4. javac rejects the later declaration. No class is built, so nothing at all is printed.

Worked example: Brackets do not count

Problem.

Exactly one marked line is rejected. Which one?

import java.util.*;
class Desk {
    void file(List<String> a) { }              // LINE 1
    void file(List<Integer> b) { }             // LINE 2
    int stamp(Set<String> s) { return 0; }     // LINE 3
    <T> void stamp(T[] t) { }                  // LINE 4
}
public class Main {
    public static void main(String[] args) {
        System.out.println("desk ready");
    }
}

What is asked.

The line number of the clash.

Idea.

Drop every pair of brackets, then look for equal pairs.

  1. file(List<String>) and file(List<Integer>) both erase to file(List).
  2. stamp(Set<String>) erases to stamp(Set); stamp(T[]) erases to stamp(Object[]). These differ, even though the return types differ too.
  3. The compiler accepts the first file and rejects the second, on LINE 2.

Answer.

LINE 2

Common mistake.

Saying List<String> and List<Integer> are different enough. They are different at compile time but identical after erasure.

When this breaks

"Different erased parameters, so two separate methods" is not the rule between a parent and a child. A child method may override a generic parent method even though the raw erasures differ. Java then adds a hidden method to connect them.

Overriding a generic parent

class Alarm<T> {
    void arm(T code) {
        System.out.println("alarm " + code);
    }
}
class DoorAlarm extends Alarm<String> {
    @Override
    void arm(String code) {
        System.out.println("door " + code);
    }
}
public class Main {
    public static void main(String[] args) {
        Alarm<String> a = new DoorAlarm();
        a.arm("k7");
    }
}

4. Arrays bend, lists do not

Is a box of owls also a box of birds? It depends on the kind of box.

when an array or list of a child type may stand where the parent type is written

Integer is a child of Number. So you may store an Integer in a Number variable. Does it follow that an array of integers may be used as an array of numbers? Run this in your head.

An array seen as its parent

public class Main {
    public static void main(String[] args) {
        Number[] slots = new Integer[2];
        slots[0] = 4;
        System.out.println(slots[0]);
        slots[1] = 2.5;
        System.out.println(slots[1]);
    }
}

The array remembers what it was built as

  1. javac allows this: an Integer[] counts as a Number[]. The object keeps its own class.
  2. Storing 4 works: the boxed value is an Integer, which this array accepts.
  3. The first line of output appears. Output made before a failure stays on the screen.
  4. The compiler saw a Number going into a Number[]. The array object refuses it while running.

Think of a shelf built for mugs only, with a card on it saying "for crockery". Someone who reads the card may try to put a plate there, and the shelf itself refuses. The analogy stops at the check: only arrays carry this knowledge while the program runs.

Why arrays are allowed to bend. Reading is safe: whatever comes out of an Owl[] really is a Bird. Writing is the danger, so each array remembers its element class and checks every store.

Why lists may not. After erasure a list has no memory of its type argument, so nothing could check a store while running. The compiler therefore forbids the risky view completely.

The list is refused

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> whole = new ArrayList<>();
        List<Number> any = whole;
        any.add(2.5);
    }
}

Worked example: Owls in a bird array

Problem.

What does this print?

class Bird {
    String call() { return "chirp"; }
}
class Owl extends Bird {
    @Override
    String call() { return "hoot"; }
}
public class Main {
    static void chorus(Bird[] flock) {
        for (Bird b : flock) {
            System.out.println(b.call());
        }
    }
    public static void main(String[] args) {
        Owl[] owls = {new Owl(), new Owl()};
        chorus(owls);
    }
}

What is asked.

The printed lines.

Idea.

The parameter type decides what is accepted; the object decides which method runs.

  1. The parameter is Bird[] and the argument is an Owl[]. Arrays are covariant, so it is accepted.
  2. Each element is an Owl object, so call() runs the owl's body.
  3. Two elements print two lines.

Answer.

hoot and hoot

Common mistake.

Expecting chirp because the variable type is Bird.

What if

chorus(Bird[] flock) accepts an Owl[] and prints hoot twice.

  • The parameter becomes List<Bird> and main passes a List<Owl>. Compile or not?
    It does not compile.. A list of owls is not a list of birds.
  • Inside chorus the first statement is flock[0] = new Bird();. What happens?
    It compiles and throws ArrayStoreException.. The object is an Owl[], which refuses a plain Bird.
  • main writes Owl[] x = new Bird[]{new Owl()};. Compile or not?
    It does not compile.. A Bird[] may hold other birds, so it cannot be treated as an Owl[].

Worked example: The written type travels back

Problem.

Both array elements are owls. Does Owl found = first(mixed); compile?

class Bird { }
class Owl extends Bird { }
public class Main {
    static <T extends Bird> T first(T[] a) {
        return a[0];
    }
    public static void main(String[] args) {
        Bird[] mixed = {new Owl(), new Owl()};
        Owl found = first(mixed);
    }
}

What is asked.

Compile or not, with the reason.

Idea.

The letter is filled from the written type of the argument, not from the objects inside.

  1. The header takes a T[] and returns a T.
  2. mixed is written as Bird[], so T must be Bird.
  3. The result is therefore a Bird to the compiler, and a Bird cannot be stored in an Owl variable without a cast.

Answer.

It does not compile.

Common mistake.

Looking at the objects. The compiler never looks inside the array.

Array parameter or list parameter

Array

Accepts Bird[], Owl[] and any other bird array.

static void count(Bird[] flock) {
    System.out.println(flock.length);
}

List

Accepts List<Bird> only.

static void count(List<Bird> flock) {
    System.out.println(flock.size());
}

The difference. Bird[] against List<Bird>.

Arrays accept child arrays; a list parameter demands exactly its type argument.

Worked example: One header for both lists

Problem.

What does this print?

import java.util.*;
class Bird {
    public String toString() { return "Bird"; }
}
class Owl extends Bird {
    public String toString() { return "Owl"; }
}
public class Main {
    static <T extends Bird> void roll(List<T> flock) {
        for (T b : flock) {
            System.out.print(b + ";");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        List<Owl> owls = new ArrayList<>();
        owls.add(new Owl());
        List<Bird> birds = new ArrayList<>();
        birds.add(new Bird());
        birds.add(new Owl());
        roll(owls);
        roll(birds);
    }
}

What is asked.

Two lines.

Idea.

A bounded letter lets each call pick its own list type.

  1. For roll(owls), T is Owl, which satisfies the bound Bird.
  2. The one owl prints Owl;.
  3. For roll(birds), T is Bird.
  4. The bird and the owl print their own text: Bird;Owl;.

Answer.

Owl;, then Bird;Owl;

Common mistake.

Thinking a bounded letter has the same limit as List<Bird>.

When this breaks

"Arrays accept a child type" does not make the store safe. A header like Bird[] accepts an Owl[], and writing any other bird into it compiles but fails while running.

5. Saying "some type"

A wildcard stands for one type that you choose not to name.

the question mark in a type argument, with and without a bound

You want one sum method for a list of integers and for a list of decimals. List<Number> accepts neither, as the last lesson showed. What can the header say instead?

Think of a sealed envelope marked "some kind of number inside". You may take the contents out and treat them as a number. You may not push your own paper in, because you do not know what kind the envelope is for. The analogy stops at null, which fits any kind.

Why reading works and adding does not. The method receives some list, perhaps of Double. Every element is surely a Number, so reading is safe. An Integer you add might not belong in a list of Double, and the compiler cannot know which list arrived.

Upper-bounded wildcard

List<? extends Number> means a list of one unknown type that is Number or a child of it.

Worked example: One sum for two lists

Problem.

What are the two lines?

import java.util.*;
public class Main {
    static double sum(List<? extends Number> xs) {
        double total = 0;
        for (Number n : xs) {
            total += n.doubleValue();
        }
        return total;
    }
    public static void main(String[] args) {
        List<Integer> a = List.of(1, 2, 3);
        List<Double> b = List.of(1.5, 2.5);
        System.out.println(sum(a));
        System.out.println(sum(b));
    }
}

What is asked.

Two printed numbers.

Idea.

Each call picks its own unknown type; the body only reads Numbers.

  1. sum(a) accepts a List<Integer>, since Integer is a Number.
  2. It adds 1.0, 2.0 and 3.0 to get 6.0.
  3. sum(b) accepts a List<Double> and adds 1.5 and 2.5 to get 4.0.

Answer.

6.0, then 4.0

Common mistake.

Writing 6 for the first line. The variable total is a double.

What if

sum(List<? extends Number> xs) prints 6.0 and 4.0.

  • Inside sum, add the statement xs.add(1);. Compile or not?
    It does not compile.. The unknown type may be Double, so an Integer cannot be added.
  • Inside sum, add xs.add(null); and pass new ArrayList<Integer>() from main. Compile or not?
    It compiles.. null is a value of every reference type.
  • The parameter becomes List<Number>. What happens to sum(a)?
    The program no longer compiles.. A List<Integer> is not a List<Number>.

A wildcard also helps a generic class look at another object of its own kind. Here a label compares its length with a second label, which may hold a different type of text. A parameter Label<S> would accept only a label with the same type argument as this one; Label<?> accepts a label with any allowed one.

Worked example: Comparing two labels

Problem.

door holds a String and jar holds a StringBuilder. What prints?

class Label<S extends CharSequence> {
    private S text;
    Label(S start) { text = start; }
    S text() { return text; }
    void rename(S next) { text = next; }
    boolean longerThan(Label<?> other) {
        return text.length() > other.text().length();
    }
}
public class Main {
    public static void main(String[] args) {
        Label<String> door = new Label<>("pantry");
        Label<StringBuilder> jar = new Label<>(new StringBuilder("rye"));
        System.out.println(door.longerThan(jar));
    }
}

What is asked.

One line.

Idea.

Label<?> accepts any label, and the class bound still gives CharSequence.

  1. door.longerThan(jar) passes a Label<StringBuilder> to a Label<?> parameter, which is allowed.
  2. other.text() has some unknown type, but the class says every S is a CharSequence, so length() exists.
  3. pantry has 6 letters and rye has 3.
  4. 6 is greater than 3.

Answer.

true

Common mistake.

Thinking nothing can be called on a value of unknown type. The class bound still applies.

What if

boolean longerThan(Label<?> other) compiles and door.longerThan(jar) prints true.

  • The body first calls other.rename(text);. Compile or not?
    It does not compile.. rename needs the unknown type of other, and nothing is known to be of that type.
  • jar is declared as Label<Integer> and built from 7. Compile or not?
    It does not compile.. Integer is outside the bound CharSequence, so no such label type exists.
  • The call becomes door.longerThan(door). What prints?
    It prints false.. A length is never greater than itself.

Unknown type or named type

Wildcard

The element read cannot be written back.

static void rotate(List<?> xs) {
    xs.set(0, xs.get(1));
}

Type variable

The same name ties the two operations together.

static <T> void rotate(List<T> xs) {
    xs.set(0, xs.get(1));
}

The difference. ? against <T> and T.

Use a letter when two places must share one type; a wildcard when you only need to accept it.

Worked example: A swap needs a name

Problem.

What does this print?

import java.util.*;
public class Main {
    static <T> void swapEnds(List<T> xs) {
        T head = xs.get(0);
        xs.set(0, xs.get(xs.size() - 1));
        xs.set(xs.size() - 1, head);
    }
    public static void main(String[] args) {
        List<String> days = new ArrayList<>(List.of("mon", "tue", "wed"));
        swapEnds(days);
        System.out.println(days);
    }
}

What is asked.

The printed list.

Idea.

T is String, so the element taken out may be put back.

  1. head receives the first element, mon.
  2. Position 0 is overwritten by the last element, wed.
  3. The last position receives head.
  4. Printing a list shows square brackets and commas.

Answer.

[wed, tue, mon]

Common mistake.

Forgetting the saved head and writing wed twice.

When this breaks

"? accepts anything" fails where a type must be created or declared. new ArrayList<?>() is rejected, and so is a method header such as static void f(<?> x). A wildcard lives only inside the brackets of a type.

6. Containers and their limits

A generic class stores items; some things it can never do with its letter.

generic classes that hold a map, and what erasure forbids inside them

A word book remembers in which position each new word was first noted, and adds up the letters of the different words. How can one generic class do that for any kind of text?

Think of a coat check with numbered tickets: you hand over a ticket and get the coat, or the attendant says there is none. A map works like that, from a key to a value. The analogy stops at one point: storing a second coat under a used ticket simply replaces the first.

Why a bound belongs here. The book calls length() on what it stored. That call is only legal if every key type surely has it. So the class declares <K extends CharSequence>.

Four map calls

CallPresent keyMissing key
get(k)the valuenull
getOrDefault(k, d)the valued
containsKey(k)truefalse
put(k, v)replaces the valueadds an entry
Notice

A short program confirms every cell of that table.

Worked example: The word book

Problem.

What does this print?

import java.util.*;
class WordBook<K extends CharSequence> {
    private final Map<K, Integer> seen = new LinkedHashMap<>();
    void note(K word) {
        if (!seen.containsKey(word)) {
            seen.put(word, seen.size() + 1);
        }
    }
    int position(K word) {
        return seen.getOrDefault(word, 0);
    }
    int letters() {
        int total = 0;
        for (K word : seen.keySet()) {
            total += word.length();
        }
        return total;
    }
}
public class Main {
    public static void main(String[] args) {
        WordBook<String> book = new WordBook<>();
        book.note("oak");
        book.note("cedar");
        book.note("oak");
        System.out.println(book.position("oak"));
        System.out.println(book.letters());
    }
}

What is asked.

Two lines.

Idea.

Fill K with String, then follow each call through the map.

  1. new WordBook<>() makes K equal to String.
  2. The first oak stores position 1 and cedar stores position 2. The second oak is already a key, so nothing changes and position("oak") is 1.
  3. letters() visits each key once: oak has 3 letters and cedar has 5, so the sum is 8.

Answer.

1, then 8

Common mistake.

Counting oak twice in letters(). A map holds each key once.

What if

The word book prints 1 and 8.

  • main declares WordBook<Integer>. Compile or not?
    It does not compile.. Integer does not satisfy the bound CharSequence.
  • The class header becomes class WordBook<K>. Compile or not?
    It does not compile.. word.length() needs the bound. An unbounded K offers only the methods of Object.
  • main also calls book.position("elm") and prints it. What prints for it?
    It prints 0.. The key was never stored, so getOrDefault returns the second argument.

Worked example: Replaced and missing

Problem.

What are the four lines?

import java.util.*;
class Registry<K, V> {
    private final Map<K, V> data = new LinkedHashMap<>();
    void add(K k, V v) { data.put(k, v); }
    V find(K k) { return data.get(k); }
    boolean has(K k) { return data.containsKey(k); }
    int size() { return data.size(); }
}
public class Main {
    public static void main(String[] args) {
        Registry<Integer, String> lockers = new Registry<>();
        lockers.add(12, "Asha");
        lockers.add(15, "Ben");
        lockers.add(12, "Chen");
        System.out.println(lockers.size());
        System.out.println(lockers.find(12));
        System.out.println(lockers.find(99));
        System.out.println(lockers.has(99));
    }
}

What is asked.

Four lines.

Idea.

Update the map in order, then answer each question from its state.

  1. add(12, "Asha") and add(15, "Ben") create two entries.
  2. add(12, "Chen") reuses key 12, so the size stays 2.
  3. find(12) gives Chen.
  4. find(99) gives null, and has(99) gives false.

Answer.

2, Chen, null, false

Common mistake.

Counting three entries.

Now the other side of erasure. Inside a class Box<T>, the code cannot create a new T() or ask whether an object is a T. While the program runs, T has been removed, so there is nothing to create or test.

What survives without the letter

You writeVerdictWhat to do instead
new T()compilation errorpass the object in
new T[3]compilation erroruse a list
o instanceof Tcompilation errorkeep a Class object
T.classcompilation errorpass a Class object in
static T shared;compilation erroruse an instance field
List<int>compilation errorList<Integer>
o instanceof List<?>acceptedonly the raw class is tested
Notice

Every row of that table is compiled by itself.

Worked example: One counter for every kind

Problem.

What does this print?

class Ticket<T> {
    static int made;
    Ticket() { made++; }
}
public class Main {
    public static void main(String[] args) {
        new Ticket<String>();
        new Ticket<Integer>();
        System.out.println(Ticket.made);
    }
}

What is asked.

One line.

Idea.

There is one class Ticket at run time, so one static field.

  1. new Ticket<String>() increases made to 1.
  2. new Ticket<Integer>() uses the same class, so made becomes 2.
  3. The static field is read through the plain class name.

Answer.

2

Common mistake.

Believing each type argument gets its own counter.

A list or an array of T

List

Allowed.

class Rack<T> {
    java.util.List<T> make() {
        return new java.util.ArrayList<T>();
    }
}

Array

Refused.

class Rack<T> {
    T[] make() {
        return new T[3];
    }
}

The difference. ArrayList<T> against T[3].

An array needs its element class while running; a list does not.

When this breaks

Casting an Object[] to T[] compiles with a warning, so it looks like a way round the rule. The array is still an Object[], and handing it out as a String[] fails while running.

The unchecked array

class Stash<T> {
    private final T[] cells;
    @SuppressWarnings("unchecked")
    Stash(int n) {
        cells = (T[]) new Object[n];
    }
    void set(int i, T v) { cells[i] = v; }
    T get(int i) { return cells[i]; }
    T[] all() { return cells; }
}
public class Main {
    public static void main(String[] args) {
        Stash<String> s = new Stash<>(2);
        s.set(0, "map");
        System.out.println(s.get(0));
        String[] out = s.all();
        System.out.println(out.length);
    }
}

Practise this topic →

Weeks covering this topic

Other Java topics