Sub topic 8
Restricting Types with Bounds
A type parameter like T can stand for any type. That flexibility has a cost. Inside your code, the compiler knows nothing about T, so you can only call methods that every object has, such as toString(). A bound is a rule that limits which types T may be. In return, you get to use the methods those types share.
The Problem: T Knows Too Little
Say you want a method that finds the largest item in a list. You need to compare items, but plain T has no compareTo method. This version does not compile:
import java.util.List;
public class BrokenMax {
public static <T> T max(List<T> list) {
T best = list.get(0);
for (T item : list) {
// if (item.compareTo(best) > 0) { } // compile error: T has no compareTo
}
return best;
}
}Adding an Upper Bound
An upper bound says "T must be this type or a subtype of it." You write it with the extends keyword. Here, T extends Comparable<T> means every T can be compared with another T.
import java.util.List;
public class MaxFinder {
public static <T extends Comparable<T>> T max(List<T> list) {
T best = list.get(0);
for (T item : list) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(max(List.of(3, 9, 4))); // 9
System.out.println(max(List.of("pear", "apple"))); // pear
}
}Integer and String both implement Comparable, so both calls work. If you passed a list of a type that is not Comparable, the compiler would reject the call.
Bounding with a Class
Bounds work with classes too. Here, T extends Number lets you call doubleValue(), which every Number has.
public class Stats<T extends Number> {
private final T[] values;
@SafeVarargs
public Stats(T... values) {
this.values = values;
}
public double average() {
double total = 0;
for (T v : values) {
total += v.doubleValue();
}
return total / values.length;
}
public static void main(String[] args) {
Stats<Integer> s = new Stats<>(2, 4, 6);
System.out.println(s.average()); // 4.0
// Stats<String> bad = new Stats<>("a"); // compile error: String is not a Number
}
}The @SafeVarargs line silences a compiler warning about generic varargs. A later chapter explains it.
What a Bound Gives You
| Declaration | Allowed types | Methods you can call on T |
|---|---|---|
| `<T>` | Any object type | Object methods only |
| `<T extends Number>` | Integer, Double, Long, ... | Number methods, such as `doubleValue()` |
| `<T extends Comparable<T>>` | String, Integer, ... | `compareTo(T)` |
Exercise
Write the header of a generic method smallest that takes a List<T> and returns a T, where T must be comparable to itself.
Show answer
public static <T extends Comparable<T>> T smallest(List<T> list)
Exercise
Given class Stats<T extends Number>, which of these compile: Stats<Double>, Stats<String>, Stats<Long>?
Show answer
Stats<Double> and Stats<Long> compile because Double and Long are subclasses of Number. Stats<String> does not compile because String is not a Number.