Common Use Cases for Bounded Type Parameters
You'll learn how bounded type parameters solve real-world programming problems by enforcing contracts and enabling operations like sorting and comparison.
The Core Idea
Bounded type parameters shine when you need to guarantee that generic types support specific operations. Instead of accepting any type, you restrict your generics to types that can do something useful—like compare themselves, perform math, or implement a required interface.
Sorting and Comparison
One of the most common use cases involves sorting. You can't sort a collection of objects unless they're comparable. Here's where <T extends Comparable<T>> comes in:
public <T extends Comparable<T>> T findMax(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
Because of the bound, you can safely call compareTo() on the type parameter. Without the bound, Java wouldn't know that T supports comparison.
Enforcing Contracts
Bounded type parameters act as compile-time contracts. If you're building a method that processes shapes, you can require that all types extend Shape:
public <T extends Shape> double calculateTotalArea(List<T> shapes) {
double total = 0;
for (T shape : shapes) {
total += shape.getArea(); // safe because T extends Shape
}
return total;
}
This prevents you from accidentally passing incompatible types and gives you access to Shape's methods.
Working with Numbers
When performing calculations, you can bound to Number to work with any numeric type while accessing methods like doubleValue():
public <T extends Number> double sum(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
Key Takeaway: Bounded type parameters enable type-safe operations by guaranteeing that generic types implement specific methods—most commonly used for sorting with Comparable, enforcing interface contracts, and performing numeric operations with Number.