Part 09 / Topic 3 of 10
Generic methods and bounded type parameters
A single method can be generic even inside a plain, non-generic class. The type parameter is declared right before the return type.
static <T> T firstOf(List<T> items) {
return items.get(0);
}
Calling firstOf(cities) never needs you to write ex.<String>firstOf(cities) — the compiler works T out from the argument you pass. This is called type inference.
Bounded type parameters
Sometimes a generic method needs to do something with the values, not just store and return them — compare two of them, for example. Object (the type every class extends, if nothing else is written) has no compareTo, so T on its own is not enough.
static <T extends Comparable<? super T>> T max(Collection<T> items) {
Iterator<T> it = items.iterator();
T best = it.next();
while (it.hasNext()) {
T next = it.next();
if (next.compareTo(best) > 0) best = next;
}
return best;
}
<T extends Comparable<? super T>> is a bound: it says "T can be anything, as long as it (or something it inherits from) is Comparable to itself." extends is used for both classes and interfaces in a bound — there is no separate implements keyword here. Without the bound, next.compareTo(best) would not compile, because plain T could be anything, including a type with no compareTo at all.
System.out.println(max(List.of("Pune", "Delhi", "Chennai"))); // Pune
System.out.println(max(List.of(1299, 499, 2999, 899))); // 2999
String and the boxed number types (Integer, Double, ...) all implement Comparable, which is why both calls compile and run with the same max method.
🔍 Going deeper — wildcards: a wildcard (
?) is used where you receive a generic type you will only read from or only write into, not both.List<? extends Number>("producer extends") means "a list of some unknown subtype ofNumber" — you can readNumbers out of it safely, but you cannot add to it, because the compiler does not know the exact subtype.List<? super Integer>("consumer super") is the opposite: you can safely addIntegers into it, because every supertype ofIntegercan certainly hold one, but you can only read it back out asObject. A common memory aid is PECS: Producer Extends, Consumer Super. You will meet this mostly when reading library method signatures (Collections.copy,Comparator.comparing) rather than writing your own — most of your own methods are fine with a plain type parameter.
Full program: examples/BoundedGenericMethods.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.