Type parameters sit inside every collection.
Open the interactive lessons →Generics and Type Erasure past questions
Contents
- A type you choose later
- What is left at run time
- Two methods, one signature
- Arrays bend, lists do not
- Saying "some type"
- 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.
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.
new Parcel<>()takes its type argument from the left side, soTisStringhere.put("socks")accepts aString.take()returns aString, so no cast is written andtoUpperCase()is allowed.
Answer.
SOCKS
Common mistake.
Writing a cast before toUpperCase(). The compiler already knows the type.
Parcel<String> stores socks and prints SOCKS.
- Add
p.put(42);after the firstput. Does it compile?
It does not compile..putnow expects aString, so the wrong value is caught on its own line. - Use
Parcel<Integer>, callput(42)and printp.take() + 1. What prints?
It prints43..take()returns anInteger, which unboxes for the addition. - Write
Parcel<int>instead ofParcel<Integer>. Does it compile?
It does not compile.. A type argument must be a reference type. Primitive types such asintare 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.
- For
lastOf(pets)the argument is aString[], soTisStringand the result haslength(). - The last pet is
eel, whose length is 3. - For
lastOf(rolls)the argument is anInteger[], soTisInteger. - 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
| Declared | Visible in | Not visible in |
|---|---|---|
class Shelf<T> | instance fields, constructors, instance methods | static fields and static methods |
<U> String label(U tag) | that method only | every other method |
static <V> V same(V v) | that method only | every 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"));
}
}
Shelf has the class letter T, a method letter U and a static method with its own V.
- Add the field
static T spare;toShelf. Compile or not?
It does not compile.. Astaticfield is shared by every kind of shelf, so it cannot have the object'sT. - Add
static void drop(T x) { }toShelf. Compile or not?
It does not compile.. Astaticmethod cannot use the class's letter. - Add
static <T> void drop(T x) { }toShelf. Compile or not?
It compiles.. The method declares a newTof 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.
- The header says
<T extends Weighable>, soaandbare at leastWeighable. Weighabledeclaresgrams(), so both calls are legal.- 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.
"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 wrote | Erased form | Reason |
|---|---|---|
T with no bound | Object | anything may be stored |
T extends B | B | every T is at least a B |
T extends B & C | B | the first bound is used |
List<T> | List | brackets and their content go |
T[] | the erased type of T, then [] | an array stays an array |
int, String | unchanged | nothing 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
- The class header loses
<T extends Number>. Remember the bound: everyTinside will become it. - Field and method use the class's
T, so both now sayNumber, notObject. Eis the method's own variable with no bound:EbecomesObject.List<E>becomes plainList.- 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.
Tbelongs to the class and has no bound, socupandpeek()useObject.Ebelongs towidthand has the boundCharSequence, so the parameter becomesCharSequence.- The return type
intis not generic and stays. T[] cupsis an array ofT, so it becomesObject[].
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.
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 fieldcupbecomesNumber,peek()returnsNumberandfilltakesNumber[];widthis unchanged.. Only the class'sTgot a bound.Ehas its own. - A parameter
T[][] gridis added tofill. What is its erased type with the original header?
It becomesObject[][].. 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.
- In
peak, the first bound ofTisNumber, so it returnsNumber, andList<T>becomesList. - In
order, the bound isComparable<T>; its brackets go too, so the parameter isComparable[]. - In
lookup,Khas no bound and becomesObject. VbecomesNumber, andMap<K, V>becomesMap.
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
| Symbol | Meaning |
|---|---|
Ljava/lang/Object; | the class between L and ; |
[ | an array of what follows |
I | int |
D | double |
Z | boolean |
V | void, no result |
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.
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.
"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.
- 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.
- The first erases to
ring(CharSequence), the second toring(Object). No clash. ring("dong"): aStringfits both, andCharSequenceis the more specific, so it printschars 4.ring(8): anIntegeris not aCharSequence, so only the second fits and printsany 8.
Answer.
chars 4, then any 8
Common mistake.
Calling it a duplicate because both are written ring(T x).
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 printsxonly. Compile or not?
It does not compile..T extends Objecterases toObject, the same as the second method. - Add
<U> void ring(U y) { }. Compile or not?
It does not compile..Uwith no bound erases toObject, which is already taken. - Add
void ring(String s) { }. Compile or not?
It compiles.. Its erased parameter isString, which no otherringhas.
Two names, one erased signature
- The first
ringerases toring(CharSequence). - The second erases to
ring(Object). The parameter types differ, so the two can live together. - A third one with
Uerases toring(Object)too. A new letter is not a new signature. javacrejects 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.
file(List<String>)andfile(List<Integer>)both erase tofile(List).stamp(Set<String>)erases tostamp(Set);stamp(T[])erases tostamp(Object[]). These differ, even though the return types differ too.- The compiler accepts the first
fileand rejects the second, onLINE 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.
"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
javacallows this: anInteger[]counts as aNumber[]. The object keeps its own class.- Storing 4 works: the boxed value is an
Integer, which this array accepts. - The first line of output appears. Output made before a failure stays on the screen.
- The compiler saw a
Numbergoing into aNumber[]. 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.
- The parameter is
Bird[]and the argument is anOwl[]. Arrays are covariant, so it is accepted. - Each element is an
Owlobject, socall()runs the owl's body. - Two elements print two lines.
Answer.
hoot and hoot
Common mistake.
Expecting chirp because the variable type is Bird.
chorus(Bird[] flock) accepts an Owl[] and prints hoot twice.
- The parameter becomes
List<Bird>andmainpasses aList<Owl>. Compile or not?
It does not compile.. A list of owls is not a list of birds. - Inside
chorusthe first statement isflock[0] = new Bird();. What happens?
It compiles and throwsArrayStoreException.. The object is anOwl[], which refuses a plainBird. mainwritesOwl[] x = new Bird[]{new Owl()};. Compile or not?
It does not compile.. ABird[]may hold other birds, so it cannot be treated as anOwl[].
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.
- The header takes a
T[]and returns aT. mixedis written asBird[], soTmust beBird.- The result is therefore a
Birdto the compiler, and aBirdcannot be stored in anOwlvariable 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.
- For
roll(owls),TisOwl, which satisfies the boundBird. - The one owl prints
Owl;. - For
roll(birds),TisBird. - 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>.
"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.
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.
sum(a)accepts aList<Integer>, sinceIntegeris aNumber.- It adds 1.0, 2.0 and 3.0 to get 6.0.
sum(b)accepts aList<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.
sum(List<? extends Number> xs) prints 6.0 and 4.0.
- Inside
sum, add the statementxs.add(1);. Compile or not?
It does not compile.. The unknown type may beDouble, so anIntegercannot be added. - Inside
sum, addxs.add(null);and passnew ArrayList<Integer>()frommain. Compile or not?
It compiles..nullis a value of every reference type. - The parameter becomes
List<Number>. What happens tosum(a)?
The program no longer compiles.. AList<Integer>is not aList<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.
door.longerThan(jar)passes aLabel<StringBuilder>to aLabel<?>parameter, which is allowed.other.text()has some unknown type, but the class says everySis aCharSequence, solength()exists.pantryhas 6 letters andryehas 3.- 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.
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..renameneeds the unknown type ofother, and nothing is known to be of that type. jaris declared asLabel<Integer>and built from7. Compile or not?
It does not compile..Integeris outside the boundCharSequence, so no such label type exists.- The call becomes
door.longerThan(door). What prints?
It printsfalse.. 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.
headreceives the first element,mon.- Position 0 is overwritten by the last element,
wed. - The last position receives
head. - Printing a list shows square brackets and commas.
Answer.
[wed, tue, mon]
Common mistake.
Forgetting the saved head and writing wed twice.
"? 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
| Call | Present key | Missing key |
|---|---|---|
get(k) | the value | null |
getOrDefault(k, d) | the value | d |
containsKey(k) | true | false |
put(k, v) | replaces the value | adds an entry |
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.
new WordBook<>()makesKequal toString.- The first
oakstores position 1 andcedarstores position 2. The secondoakis already a key, so nothing changes andposition("oak")is 1. letters()visits each key once:oakhas 3 letters andcedarhas 5, so the sum is 8.
Answer.
1, then 8
Common mistake.
Counting oak twice in letters(). A map holds each key once.
The word book prints 1 and 8.
maindeclaresWordBook<Integer>. Compile or not?
It does not compile..Integerdoes not satisfy the boundCharSequence.- The class header becomes
class WordBook<K>. Compile or not?
It does not compile..word.length()needs the bound. An unboundedKoffers only the methods ofObject. mainalso callsbook.position("elm")and prints it. What prints for it?
It prints0.. The key was never stored, sogetOrDefaultreturns 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.
add(12, "Asha")andadd(15, "Ben")create two entries.add(12, "Chen")reuses key 12, so the size stays 2.find(12)givesChen.find(99)givesnull, andhas(99)givesfalse.
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 write | Verdict | What to do instead |
|---|---|---|
new T() | compilation error | pass the object in |
new T[3] | compilation error | use a list |
o instanceof T | compilation error | keep a Class object |
T.class | compilation error | pass a Class object in |
static T shared; | compilation error | use an instance field |
List<int> | compilation error | List<Integer> |
o instanceof List<?> | accepted | only the raw class is tested |
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.
new Ticket<String>()increasesmadeto 1.new Ticket<Integer>()uses the same class, somadebecomes 2.- 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.
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);
}
}