Sub topic 8
Restricting Types with Bounds
In the last chapter you wrote generic methods that accept any type T. That freedom has a cost. If T can be anything, the compiler only knows that T is some kind of Object. You can store it, return it, and print it, but you cannot call methods like compareTo or doubleValue on it.
A bound fixes this. A bound is a rule that limits which types can fill in a type parameter. In return for the limit, you get to use the methods that every allowed type is guaranteed to have.
The Problem: T Knows Too Little
Say you want a method that finds the largest item in a list. A first try might look like this:
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
best = item;
}
}
return best;
}
}This does not compile. The error says something like "cannot find symbol: method compareTo(T)". The compiler is right. Someone could call max with a list of Thread objects, and threads cannot be compared. Since T might be any type, the compiler only allows the methods that every object has, such as toString and equals.
The Fix: An Upper Bound
You add a bound with the extends keyword inside the angle brackets:
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) {
Integer m = max(List.of(3, 9, 4));
String w = max(List.of("pear", "apple", "zebra"));
System.out.println(m); // 9
System.out.println(w); // zebra
}
}Read <T extends Comparable<T>> as: "T can be any type, as long as it can be compared with other T values." Comparable is a built-in Java interface with one method, compareTo. Integer, String, Double, and LocalDate all implement it.
This is called an upper bound. It sets a ceiling: T must be Comparable<T> or something below it in the type hierarchy.
What the Bound Gives You and What It Costs
A bound works in two directions at once.
| Who | Effect of `<T extends Comparable<T>>` |
|---|---|
| Inside the method | You may call `compareTo` on any `T` value. |
| The caller | You may only pass types that implement `Comparable`. |
The caller side is checked at compile time. Try passing a type that is not comparable:
import java.util.List;
public class BoundCheck {
static class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
public static void main(String[] args) {
List<Point> points = List.of(new Point(1, 2), new Point(3, 4));
// Point p = MaxFinder.max(points); // compile error: Point is not Comparable<Point>
System.out.println(points.size());
}
}If you remove the // from that line, the compiler refuses. The error appears while you are writing the code, not when a user runs the program. Finding mistakes early is the whole point of generics.
Bounding with a Class
A bound can also be a class. Number is the parent class of Integer, Double, Long, and the other number wrapper types. Every Number has a doubleValue() method.
import java.util.List;
public class Stats {
public static <T extends Number> double average(List<T> values) {
double total = 0;
for (T v : values) {
total += v.doubleValue(); // allowed because T is a Number
}
return total / values.size();
}
public static void main(String[] args) {
System.out.println(average(List.of(1, 2, 3, 4))); // 2.5
System.out.println(average(List.of(1.5, 2.5))); // 2.0
// average(List.of("a", "b")); // compile error: String is not a Number
}
}Without the bound, v.doubleValue() would not compile.
Bounded Generic Classes
Bounds work on classes too, not only methods. You put the bound where you declare the type parameter:
public class NumberBox<T extends Number> {
private final T value;
public NumberBox(T value) {
this.value = value;
}
public boolean isPositive() {
return value.doubleValue() > 0;
}
public static void main(String[] args) {
NumberBox<Integer> a = new NumberBox<>(5);
NumberBox<Double> b = new NumberBox<>(-1.5);
// NumberBox<String> c = new NumberBox<>("hi"); // compile error
System.out.println(a.isPositive()); // true
System.out.println(b.isPositive()); // false
}
}Every method in NumberBox can treat value as a Number.
The Version You Will See in Real Code
In the Java library and in many codebases, the max signature is written a little differently:
import java.util.List;
public class MaxFinderFlexible {
public static <T extends Comparable<? super 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
}
}The ? super T part is a wildcard. Later chapters explain wildcards. For now, it means "T can be compared with itself or with one of its parent types." That makes the method accept a few more types, such as a subclass whose parent implements Comparable. For most everyday types, both versions behave the same.
Edge Cases and Common Mistakes
- Empty lists.
list.get(0)throwsIndexOutOfBoundsExceptionif the list is empty. The bound checks types, not values. Checklist.isEmpty()first, or return a fallback value. - Null elements. If the list contains
null, callingitem.compareTo(best)throwsNullPointerException. A bound does not prevent nulls. - Forgetting the type argument on Comparable.
<T extends Comparable>compiles, but it uses a raw type and gives an "unchecked" warning. Always writeComparable<T>. - Using
implements.<T implements Comparable<T>>is a syntax error. Useextends. - Bounds on the wrong side. The bound goes in the declaration (
<T extends Number>), not at the call. When you call the method, you just pass a value, and the compiler infersT. - Primitives.
intcannot beT, even with aNumberbound. Java automatically wrapsintvalues intoInteger, which is whyList.of(1, 2, 3)works.
How It Works Behind the Scenes
At runtime, Java removes the type parameters. This process is called type erasure, and a later chapter covers it. With a bound, the compiler replaces T with its bound instead of Object. So in compiled code, NumberBox<T extends Number> stores its value as a Number. That is why calling doubleValue() works at runtime without any casts.
Summary
- An unbounded
Tonly lets you useObjectmethods. <T extends X>limitsTtoXor its subtypes, whereXcan be a class or an interface.- Inside the code you gain the methods of
X. Callers are limited to types that fit. - The compiler checks every call, so a wrong type is a compile error, not a runtime crash.
Exercise
Write a generic method largerOf(a, b) that takes two values of the same type and returns the larger one. It should work for Integer and String but refuse to compile for a type that cannot be compared. What does its signature look like?
Show answer
public static <T extends Comparable<T>> T largerOf(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } The bound T extends Comparable<T> allows the call to compareTo and rejects non-comparable types at compile time.
Exercise
Why does public static <T> double total(List<T> xs) { double s = 0; for (T x : xs) s += x.doubleValue(); return s; } fail to compile, and what one change fixes it?
Show answer
T has no bound, so the compiler only knows it is an Object, and Object has no doubleValue method. Change the declaration to <T extends Number> so every T is guaranteed to have doubleValue.
Exercise
Given class Box<T extends Number>, which of these compile: Box<Integer>, Box<Double>, Box<String>, Box<Number>?
Show answer
Box<Integer>, Box<Double>, and Box<Number> compile because each is Number or a subclass of Number. Box<String> does not compile because String is not a Number.