The Plain Picture#
One blueprint for a box, with a blank on the label: "Box of ____". When you order one, you fill in the blank: box of shoes, box of books. Same blueprint, checked contents.
The Real Names#
A generic class declares type parameters in angle brackets:
class Box<T>.Tis a placeholder filled in when the class is used.Conventional names:
Ttype,Eelement,Kkey,Vvalue,Rresult,A,Bfor several.The diamond operator
<>lets Java infer the type from the left side:Box<String> b = new Box<>("Priya");A generic method declares its own type parameter before the return type:
static <T> T first(List<T> items).Type arguments must be object types —
Box<Integer>, neverBox<int>(Ch 9 explains why; wrappers are from Classes, Objects and Memory Ch 8).
Under the Hood#
class Box<T> {
private T value;
Box(T value) {
this.value = value;
}
T get() {
return value;
}
}
record Pair<A, B>(A first, B second) {} // records can be generic too (03_java_oop.md Ch 12)
Box<String> b = new Box<>("Priya");
String name = b.get(); // no cast
Pair<String, Integer> p = new Pair<>("Priya", 200);
System.out.println(name + " " + p); // Priya Pair[first=Priya, second=200]Types you'll write constantly in DSA (collections in Collections, From the Inside):
List<Integer> a growable list of numbers
Map<String, Integer> word → count
Map<Integer, List<Integer>> node → its neighbours (a graph)
Set<List<Integer>> unique triplets (e.g. the "3Sum" problem)
PriorityQueue<int[]> a heap of [distance, node] pairs (arrays are objects, so int[] is allowed)Check yourself
3 questionsWhat does the T in class Box<T> mean?
Show answerHide answer
A type parameter: a placeholder for whatever type is supplied when the class is used.
What does <> do in new Box<>("x")?
Show answerHide answer
Lets the compiler infer the type argument from context.
Why is List<int> illegal but List<int[]> legal?
Show answerHide answer
Type arguments must be reference (object) types; int is a primitive, but int[] is an array — an object.