Part 09 / Topic 2 of 10
Writing your own generic class
A generic class can take more than one type parameter, one per kind of value it needs to hold.
Real-world example: a Pair<K, V> that pairs any key with any value — an order ID with its total, a city with its temperature, anything.
class Pair<K, V> {
private final K key;
private final V value;
Pair(K key, V value) {
this.key = key;
this.value = value;
}
K key() { return key; }
V value() { return value; }
@Override
public String toString() { return key + " -> " + value; }
}
Pair<String, Integer> orderTotal = new Pair<>("ORD-1001", 2499);
System.out.println(orderTotal); // ORD-1001 -> 2499
A List<Pair<String, Integer>> works exactly like any other List — generics compose, so a generic class can itself be the type parameter of a collection.
Type erasure
At compile time, Box<String> and Box<Integer> are two different, checked types. At run time, both collapse to the same single class: Box. This is type erasure — the compiler uses the type parameter to check your code, then throws that information away before the bytecode is produced.
Box<String> stringBox = new Box<>();
Box<Integer> integerBox = new Box<>();
System.out.println(stringBox.getClass() == integerBox.getClass()); // true
This is why you cannot write new T() or T[] array = new T[10] inside a generic class (there is no T left at run time to ask), and why instanceof Box<String> does not compile — only instanceof Box<?> does. None of this is something you need to work around often; it only matters when a generic program suddenly refuses to compile for a reason that looks like it should be fine.
Full program: examples/GenericBox.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.