Show contents
Chapter 1 of 7 · 20 min
Generics in depth
By the end of this chapter, you'll be able to
- Write a generic class and a generic method
- Bound a type parameter with extends
- Choose between ? extends and ? super depending on whether the collection produces or consumes
- Explain type erasure and its consequences
Generic classes and methods
A type parameter (T, A, K…) is a variable that stands for a type. It is declared between angle brackets, on the class or before a method's return type:
record Pair<A, B>(A first, B second) {
Pair<B, A> swap() {
return new Pair<>(second, first);
}
}
<T extends Comparable<? super T>> T largest(List<T> elements) {
if (elements.isEmpty()) {
throw new IllegalArgumentException("empty list");
}
T best = elements.getFirst();
for (T e : elements) {
if (e.compareTo(best) > 0) {
best = e;
}
}
return best;
}
double sum(List<? extends Number> numbers) {
double total = 0;
for (Number n : numbers) {
total += n.doubleValue();
}
return total;
}
void fill(List<? super Integer> target, int n) {
for (int i = 1; i <= n; i++) {
target.add(i);
}
}
void main() {
Pair<String, Integer> p = new Pair<>("Nairobi", 4_400_000);
IO.println(p + " -> " + p.swap());
IO.println(largest(List.of(3, 17, 8)));
IO.println(largest(List.of("kiwi", "mango", "banana")));
IO.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(0.5, 1.25)));
List<Number> numbers = new ArrayList<>();
fill(numbers, 3);
numbers.add(2.5);
IO.println(numbers);
}
Pair[first=Nairobi, second=4400000] -> Pair[first=4400000, second=Nairobi]
17
mango
6.0 1.75
[1, 2, 3, 2.5]
Pair<A, B>works with any types;new Pair<>(…)lets the compiler infer the types (the "diamond" operator).<T extends Comparable<? super T>>is a bound:Tmust know how to compare itself.largesttherefore acceptsIntegerandString, but would reject a list ofPair. The? super Talso allows types whose parent implementsComparable.List<? extends Number>accepts aList<Integer>or aList<Double>: you can readNumbervalues, but not add elements (the exact type is unknown).List<? super Integer>accepts aList<Integer>,List<Number>orList<Object>: you can addIntegervalues.
Producing or consuming: the PECS rule
The mnemonic PECS (Producer Extends, Consumer Super) settles it every time:
| The collection… | Wildcard | Example |
|---|---|---|
| produces values you read | ? extends T | sum(List<? extends Number>) |
| consumes values you add | ? super T | fill(List<? super Integer>) |
| does both | exact T, no wildcard | void sort(List<T>) |
That's exactly the signature of Collections.copy(List<? super T> dest, List<? extends T> src) in the standard library: the source produces, the destination consumes.
Type erasure
Generics exist only during compilation. The compiler checks the types, then erases them: at run time, a List<String> and a List<Integer> are both plain Lists. This is called type erasure, a choice made to stay compatible with pre-2004 Java.
At run time, a single class: impossible to write new T() or instanceof List<String>.
Text description of the animation
- In the source code, the types are precise.
- The compiler checks every use: impossible to treat first as a number.
- A dangerous assignment is rejected here, before anything runs.
- In the bytecode, A and B become Object; a T bounded by Comparable becomes Comparable.
- At run time, a single class: impossible to write new T() or instanceof List<String>.
Practical consequences: you can't write new T(), nor new T[10], nor test x instanceof List<String>. If a method really needs the type at run time, pass it a Class<T> parameter.
Your turn
Worked exercise
Solved exercise: the key of the largest value
Write a generic method keyOfMax(Map<K, V> table) that returns the key associated with the largest value, in an empty Optional if the table is empty. It must work with any key type and any comparable value type. Test it with cities and their population, with integer codes mapped to animal names, then with an empty table.
Hint 1
<K, V extends Comparable<? super V>>. Only the value needs to be comparable.Hint 2
table.entrySet(), keeping the best entry seen so far; Optional.ofNullable(key) returns an empty Optional if key is null.Show the solution and common mistakes
<K, V extends Comparable<? super V>> Optional<K> keyOfMax(Map<K, V> table) {
K bestKey = null;
V max = null;
for (Map.Entry<K, V> e : table.entrySet()) {
if (max == null || e.getValue().compareTo(max) > 0) {
bestKey = e.getKey();
max = e.getValue();
}
}
return Optional.ofNullable(bestKey);
}
void main() {
Map<String, Integer> population = new TreeMap<>(Map.of("Kigali", 1_700_000, "Quito", 2_800_000, "Hanoi", 8_400_000));
IO.println(keyOfMax(population).orElse("none"));
Map<Integer, String> codes = Map.of(1, "zebra", 2, "antelope");
IO.println(keyOfMax(codes).orElse(-1));
IO.println(keyOfMax(new HashMap<String, Double>()).orElse("none"));
}
Hanoi
1
none
For the codes, the values are Strings: "zebra" is the greatest in alphabetical order, hence the key 1. The same method serves two very different uses, and the compiler checks both.
Common mistakes:
- Writing
<K, V>without a bound:compareTodoesn't exist on an arbitraryV, and the code doesn't compile. - Returning
nullinstead of an emptyOptional: the caller forgets the empty-table case and gets aNullPointerExceptionfurther on.
Summary
- 1A type parameter (<T>) makes a class or method reusable, with compile-time checking.
- 2extends bounds a type parameter: <T extends Comparable<? super T>> requires a comparable type.
- 3PECS: ? extends for a collection you read, ? super for a collection you fill.
- 4Generics are invariant: a List<String> isn't a List<Object>.
- 5Types are erased at run time: no new T(), no instanceof List<String>.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.