The Plain Picture#
"Box of ____ — must be something that can be measured." You can fill the blank with apples or bananas, not with "happiness".
The Real Name#
A bounded type parameter restricts which types are allowed, so the code inside can use their methods. <T extends X> means "T must be X
or a subtype of X" (for interfaces too — generics always say extends, never implements).
static <T extends Comparable<T>> T maxOf(List<T> items) {
// T must be comparable to itself
T best = items.get(0);
for (T x : items) {
if (x.compareTo(best) > 0) best = x; // compareTo is allowed BECAUSE of the bound
}
return best;
}
System.out.println(
maxOf(List.of(72, 95, 60)) + " " + maxOf(List.of("Priya", "Aisha", "Rahul"))
);
// 95 RahulOne method works for integers, strings, and any class implementing Comparable — and the compiler rejects types that can't be compared.
Without the bound, x.compareTo(...) wouldn't compile, because an unknown T might not have that method.
Multiple bounds: <T extends Number & Comparable<T>> (a class first, then interfaces, joined by &).
Check yourself
2 questionsWhat does <T extends Comparable<T>> allow the method to do?
Show answerHide answer
Call compareTo on values of type T, and reject types that aren't comparable.
Why does maxOf(List.of("Priya", "Aisha", "Rahul")) return "Rahul"?
Show answerHide answer
Strings compare in dictionary order, and "Rahul" comes last.