Generics · Topic 4 of 7
Bounded types
Definition​
A bounded type parameter limits which types are allowed, using extends. Inside the method you can then call the methods of the bound, such as compareTo.
Example code​
A max method that only accepts things that can be compared
import java.util.List;
class Util {
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item; // allowed because T is Comparable
}
return best;
}
}
class Demo {
public static void main(String[] args) {
System.out.println(Util.max(List.of(3, 9, 4)));
System.out.println(Util.max(List.of("pear", "apple", "zebra")));
// Util.max(List.of(new Object())); // compile error: Object is not Comparable
}
}
// Output:
// 9
// zebra
Finished this page? Track your progress (saved only in your browser).