What are bounded type parameters in Java, and how do you use them to write a useful generic method?
A bounded type parameter is a type parameter with a limit on what it can be. The limit is written after the word extends, and it lets you use the methods of that limit on values of the type parameter.
Without a bound, a type parameter is only as useful as Object, because that is all the compiler knows about it. With a bound, the compiler knows more and lets you call the methods of the bound type.
import java.util.List;
public class Main {
public static void main(String[] args) {
// The method works for any type that can be compared.
System.out.println("max of ints : " + max(3, 9, 4));
System.out.println("max of doubles : " + max(3.5, 9.1, 4.2));
System.out.println("max of strings : " + max("apple", "pear", "orange"));
// The bound has to name the type parameter as well, so that
// the comparison works with the type that was given.
System.out.println("max of a list : " + maxOf(List.of(4, 7, 2)));
}
// The bound says that T must be able to compare itself with
// another T.
static <T extends Comparable<T>> T max(T first, T second, T third) {
T best = first;
if (second.compareTo(best) > 0) {
best = second;
}
if (third.compareTo(best) > 0) {
best = third;
}
return best;
}
static <T extends Comparable<T>> T maxOf(List<T> list) {
T best = list.get(0);
for (int index = 1; index < list.size(); index++) {
if (list.get(index).compareTo(best) > 0) {
best = list.get(index);
}
}
return best;
}
}
So what does the bound buy you? It buys you the compareTo method. Without the bound, the compiler would refuse the line second.compareTo(best), because it does not know that the type parameter has that method.
There are two ways to write the bound, and the difference is worth knowing. The form <T extends Comparable<T>> means that the type must be able to compare itself with another of the same type. The form <T extends Comparable> is weaker, because it only says that the type is comparable with something, and it lets the compiler complain in a confusing way later. The stronger form is almost always the one you want.
You can also have more than one bound, separated by the & character, and you can put a class there as well as an interface.
The next question in this topic looks at a limit that surprises people.