Sub topic 9
Combining Multiple Bounds
In the last chapter you put one bound on a type parameter, for example <T extends Comparable<T>>. Sometimes one bound is not enough. You may need a type that is a number and can also be compared. Java lets you list several bounds at once. This chapter shows how.
What a Multiple Bound Is
A bound is a rule that limits which types can fill a type parameter. A multiple bound is a list of rules joined with the & symbol. The type the caller picks must follow every rule in the list.
Here is the shape:
public class Shape<T extends Number & Comparable<T>> {
private final T value;
public Shape(T value) {
this.value = value;
}
public T get() {
return value;
}
}Read T extends Number & Comparable<T> as "T must be a Number and T must be Comparable to itself." Integer passes both checks, so Shape<Integer> works. String is comparable but is not a number, so Shape<String> is a compile error.
Why You Would Want Two Bounds
Each bound gives you methods you can call on T.
- The
Numberbound lets you calldoubleValue(),intValue(), and the otherNumbermethods. - The
Comparable<T>bound lets you callcompareTo().
With both bounds, you can use both sets of methods inside the same code. With only one bound, the compiler would reject calls to the methods from the other one.
A Worked Example
The method below takes a list of numbers. It finds the smallest value, the largest value, and the average. Finding min and max needs compareTo. Finding the average needs doubleValue. So the method needs both bounds.
import java.util.List;
public class BoundsDemo {
static <T extends Number & Comparable<T>> String describe(List<T> values) {
T max = values.get(0);
T min = values.get(0);
double total = 0;
for (T v : values) {
if (v.compareTo(max) > 0) {
max = v; // uses the Comparable bound
}
if (v.compareTo(min) < 0) {
min = v;
}
total += v.doubleValue(); // uses the Number bound
}
double average = total / values.size();
return "min=" + min + ", max=" + max + ", average=" + average;
}
public static void main(String[] args) {
System.out.println(describe(List.of(4, 9, 2)));
System.out.println(describe(List.of(1.5, 0.5)));
// describe(List.of("a", "b")); // compile error: String is not a Number
}
}Save it as BoundsDemo.java, then run:
javac BoundsDemo.java
java BoundsDemoThe output is:
min=2, max=9, average=5.0
min=0.5, max=1.5, average=1.0In the first call the compiler infers T as Integer, and in the second call it infers Double. Both types extend Number and both implement Comparable to themselves, so both calls compile.
Bounds Made of Your Own Interfaces
The bounds do not have to be built-in types. You can combine your own interfaces too. This example uses a record, which is a short way to write a class that just holds data (Java 16 and later).
interface Named {
String name();
}
interface Priced {
double price();
}
record Book(String name, double price) implements Named, Priced {}
record Person(String name) implements Named {}
public class LabelDemo {
static <T extends Named & Priced> String label(T item) {
return item.name() + ": $" + item.price();
}
public static void main(String[] args) {
System.out.println(label(new Book("Java Basics", 29.5)));
// label(new Person("Ada")); // compile error: Person is not Priced
}
}This prints Java Basics: $29.5. A Book is both Named and Priced, so it is accepted. A Person is only Named, so the compiler rejects it before the program ever runs.
The Rules for Multiple Bounds
Java has a few strict rules about how you write the list.
| Rule | Allowed | Not allowed |
|---|---|---|
| Use `&` to join bounds | `T extends A & B` | `T extends A, B` |
| At most one class | `T extends Number & Comparable<T>` | `T extends Number & String` |
| The class must come first | `T extends Number & Comparable<T>` | `T extends Comparable<T> & Number` |
| Any number of interfaces | `T extends Named & Priced & Runnable` | (no limit) |
| No other type parameter in a multi-bound list | `T extends U` alone | `T extends U & Comparable<T>` |
The "one class" rule follows from how Java works: a class can only extend one other class. No type could be a Number and a String at once, so Java does not let you ask for that.
The order rule in action
If you put an interface before the class, javac stops with an error like this:
error: interface expected here
static <T extends Comparable<T> & Number> void bad(T x) { }
^The compiler expects everything after the first & to be an interface. Number is a class, so the code is rejected. To fix it, move Number to the front.
Gotchas and Edge Cases
The first bound matters later
When Java compiles generic code, it replaces T with its first bound. You will learn more about this in the chapter on type erasure. For now, remember one habit: put the most important type first. If there is a class in the list, it has to be first anyway.
Wildcards cannot use `&`
Multiple bounds only work on a type parameter you declare, like <T extends A & B>. A wildcard such as List<? extends A & B> is not allowed. If you need both bounds, declare a named type parameter.
Comparable to what?
In these examples we wrote Comparable<T>. That works for Integer, Double, and String, because each one compares to its own type. Some class hierarchies only implement Comparable on a parent class. For those, the more flexible form is Comparable<? super T>, which you saw in the max example earlier in this tutorial. Both forms can be used in a multiple bound.
Interfaces only, no class
You don't need a class in the list at all. <T extends Named & Priced> uses only interfaces. In that case the order rule doesn't apply, but the first interface is still the one Java uses when it erases T.
Summary
- Join bounds with
&:<T extends A & B & C>. - The type argument must satisfy every bound.
- Inside the code you can call methods from all of the bounds.
- You can have at most one class, and it must be listed first.
- Bounds on wildcards cannot use
&.
Exercise
Will this declaration compile? static <T extends Runnable & Thread> void start(T t) { } If not, how do you fix it?
Show answer
No. Thread is a class and Runnable is an interface, so the class must come first. Write static <T extends Thread & Runnable> void start(T t) { }. (It compiles, though the Runnable bound adds nothing, because Thread already implements Runnable.)
Exercise
Write the header of a generic method total that accepts a List<T> where every T must be both a Number and Comparable to itself, and returns a double.
Show answer
static <T extends Number & Comparable<T>> double total(List<T> list)
Exercise
Using the LabelDemo example, which of these calls compile: label(new Book("A", 1.0)), label(new Person("B"))? Explain why.
Show answer
Only the Book call compiles. Book implements both Named and Priced. Person implements only Named, so it fails the Priced bound and the compiler reports an error.
Exercise
What is wrong with <T extends Number, Comparable<T>> if you meant to give T two bounds?
Show answer
The comma declares a second type parameter named Comparable instead of adding a bound. Use & instead: <T extends Number & Comparable<T>>.