Sub topic 9
Combining Multiple Bounds
In the last chapter, you limited a type parameter with one bound, such as <T extends Comparable<T>>. Sometimes one bound is not enough. You may need a type that is a number and can be compared. Java lets you ask for both at once.
What a Multiple Bound Is
A multiple bound is a list of types that a type parameter must match, all at the same time. You join the types with the & symbol:
public class Example<T extends Number & Comparable<T>> {
}Read it as: "T must be a Number, and T must also be Comparable to itself." A type argument is accepted only if it meets every bound in the list.
Why It Matters
Each bound gives you methods you can call on T. With Number you get doubleValue(). With Comparable you get compareTo(). A multiple bound lets you use both kinds of methods in one place, and the compiler still checks every call.
A Worked Example
This method finds the largest value in a list. It uses compareTo from Comparable and doubleValue from Number.
import java.util.List;
public class BoundsDemo {
static <T extends Number & Comparable<T>> String describeLargest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) { // from Comparable
best = item;
}
}
double half = best.doubleValue() / 2; // from Number
return "Largest: " + best + ", half of it: " + half;
}
public static void main(String[] args) {
System.out.println(describeLargest(List.of(3, 9, 4)));
System.out.println(describeLargest(List.of(1.5, 0.2, 7.25)));
// describeLargest(List.of("a", "b")); // compile error: String is not a Number
}
}Output:
Largest: 9, half of it: 4.5
Largest: 7.25, half of it: 3.625Integer and Double both extend Number and implement Comparable, so both work. String is Comparable, but it is not a Number, so the compiler rejects it.
The Ordering Rule
The bounds must follow these rules:
| Rule | Example | Result |
|---|---|---|
| At most one class | `<T extends Number & Integer>` | Compile error |
| The class comes first | `<T extends Comparable<T> & Number>` | Compile error |
| Any number of interfaces after the class | `<T extends Number & Comparable<T> & java.io.Serializable>` | Compiles |
| Only interfaces is fine | `<T extends Runnable & AutoCloseable>` | Compiles |
These rules follow from how Java classes work. A class can extend only one class but can implement many interfaces, so a type parameter's bounds can include only one class too.
Exercises
Exercise
Will <T extends Runnable & Thread> compile? Why or why not?
Show answer
No. Thread is a class and Runnable is an interface. The class must come first, so it should be written <T extends Thread & Runnable>.
Exercise
With the bound <T extends Number & Comparable<T>>, can you call describeLargest(List.of(5L, 2L)), using Long values?
Show answer
Yes. Long extends Number and implements Comparable<Long>, so it meets both bounds.