Java Bounded Type Parameters
A bound limits the types a type parameter accepts. With <T extends Number>, a method can call number methods like doubleValue on its values.
A sum over any number type
sum adds two values through doubleValue. Integer and Double arguments both fit the Number bound.
public class Main {
static <T extends Number> double sum(T first, T second) {
return first.doubleValue() + second.doubleValue();
}
public static void main(String[] args) {
System.out.println(sum(10, 20));
System.out.println(sum(2.5, 1.5));
}
}Text breaks the bound
The same sum method is called with two strings. String does not fit under Number, so the compiler refuses the call.
public class Main {
static <T extends Number> double sum(T first, T second) {
return first.doubleValue() + second.doubleValue();
}
public static void main(String[] args) {
System.out.println(sum("ten", "five"));
}
}The largest of three
The Comparable bound gives the method compareTo. The same method picks the largest score and the largest name.
public class Main {
static <T extends Comparable<T>> T largest(T a, T b, T c) {
T best = a;
if (b.compareTo(best) > 0) {
best = b;
}
if (c.compareTo(best) > 0) {
best = c;
}
return best;
}
public static void main(String[] args) {
System.out.println(largest(40, 70, 55));
System.out.println(largest("Ana", "Cid", "Ben"));
}
}Example
public class Main {
static <T extends Number> double sum(T first, T second) {
return first.doubleValue() + second.doubleValue();
}
static <T extends Comparable<T>> T largest(T a, T b, T c) {
T best = a;
if (b.compareTo(best) > 0) {
best = b;
}
if (c.compareTo(best) > 0) {
best = c;
}
return best;
}
public static void main(String[] args) {
System.out.println(sum(5, 7));
System.out.println(largest(3, 9, 6));
System.out.println(largest("Ana", "Dee", "Ben"));
}
}Key points
- A bound written with extends names the parent type every argument must fit under.
- Number is the parent of Integer and Double, so both fit the bound.
- A String argument breaks the bound, and the compiler refuses the call.
- The bound <T extends Comparable<T>> gives a method compareTo on its values.
- Bounds turn a generic method from holding values into working with what the values can do.
In this example, the Number bound lets sum read doubleValue from its arguments, and the Comparable bound lets largest rank its three values. Each bound promises exactly the methods its body calls.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the bound in <T extends Number> promise?