Bounded Type Parameters in Java Generics: extends and Multiple Bounds
Learn how to restrict Java type variables with bounds: why <T extends Comparable<T>> lets you call compareTo, why extends is used for interfaces, multiple bounds with &, the class-first rule, bounded generic classes, and the LocalDate surprise.
kvi5hnuCode Sprout team member7 min readOn this page
A type variable like T stands for "any type", and that's a problem when your code needs to do something with its values. If T can be anything, the compiler only lets you call the methods of Object. Bounds solve this: they restrict a type variable to subtypes of a given class or interface, and in return give you access to that type's methods.
The problem: what can you do with a T?
Here is a generic method that should find the smallest element of an array:
class ArrayAlg {
public static <T> T min(T[] a) { // almost correct
if (a == null || a.length == 0) return null;
T smallest = a[0];
for (int i = 1; i < a.length; i++)
if (smallest.compareTo(a[i]) > 0) smallest = a[i];
return smallest;
}
}
It doesn't compile. smallest has type T, which could be any class at all. How would the compiler know that it has a compareTo method?
The solution: a bound
Restrict T to classes that implement Comparable, the standard interface with the single method compareTo. You do that with a bound on the type variable:
public static <T extends Comparable<T>> T min(T[] a) . . .
Now min can only be called with arrays of types that implement Comparable, such as String, Integer and BigDecimal. Inside the method, the compiler knows that every T has compareTo. A call with an array of, say, Rectangle objects, which aren't Comparable, is a compile-time error.

Why extends, even for interfaces?
You might wonder why the keyword is extends rather than implements. After all, Comparable is an interface. The notation
<T extends BoundingType>
means "T is a subtype of the bounding type". Both T and the bounding type can be a class or an interface. The language designers chose extends as a reasonable approximation of "subtype" rather than adding a new keyword such as sub.
Multiple bounds
A type variable can have several bounds, separated by ampersands. Commas already separate type variables:
T extends Comparable<T> & Serializable
The same rules apply as for Java inheritance:
- You can have as many interface bounds as you like.
- At most one bound can be a class.
- If there's a class bound, it must be first in the list.
class Archive<T extends Document & Comparable<T> & Serializable> { . . . } // OK
class Broken<T extends Comparable<T> & Document> { . . . } // ERROR: class must come first
Inside Archive, values of type T have the methods of Document and Comparable<T> and Serializable. The demo uses both: it sorts the items with compareTo and reads their titles with a Document method.
Another useful combination is "a number that can be compared to itself":
public static <T extends Number & Comparable<T>> T clamp(T value, T low, T high)
Bounded generic classes
Bounds work for generic classes as well as methods. A statistics class that needs numeric values can require Number:
class Stats<T extends Number> {
private final List<T> values;
. . .
double average() {
double sum = 0;
for (T v : values) sum += v.doubleValue(); // every T is a Number
return sum / values.size();
}
}
Stats<Double> and Stats<Integer> are fine. Stats<String> doesn't compile.
A generic minmax
Earlier, minmax only worked for strings. With a bound, it works for any comparable type:
public static <T extends Comparable<? super T>> Pair<T> minmax(T[] a) {
if (a == null || a.length == 0) return null;
T min = a[0];
T max = a[0];
for (int i = 1; i < a.length; i++) {
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
The demo calls it with an array of LocalDate objects, the release dates of a few Java versions, and gets the earliest and latest.
A complete example
import java.io.Serializable;
import java.time.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. a bounded generic method: T must be Comparable
LocalDate[] releases = {
LocalDate.of(2014, 3, 18), // Java 8
LocalDate.of(1996, 1, 23), // JDK 1.0
LocalDate.of(2021, 9, 14), // Java 17
LocalDate.of(2023, 9, 19), // Java 21
};
Pair<LocalDate> mm = ArrayAlg.minmax(releases);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
System.out.println("smallest word: " + ArrayAlg.min(new String[] { "pear", "apple", "fig" }));
System.out.println("smallest number: " + ArrayAlg.min(new Integer[] { 42, 7, 19 }));
System.out.println("empty array: " + ArrayAlg.min(new Integer[0]));
// ArrayAlg.min(new Object[] { ... }) // won't compile: Object is not Comparable
// LocalDate first = ArrayAlg.min(releases); // won't compile: see the LocalDate note
// 2. a bounded generic class: T must be a Number, so doubleValue() is available
var temps = new Stats<Double>(List.of(21.5, 23.0, 19.5));
var counts = new Stats<Integer>(List.of(3, 4, 8));
System.out.printf("average temperature %.2f, average count %.2f%n", temps.average(), counts.average());
// new Stats<String>(...) // won't compile: String is not a Number
// 3. multiple bounds: a Number that is also Comparable to itself
System.out.println("clamp(15, 0, 10) = " + ArrayAlg.clamp(15, 0, 10));
System.out.println("clamp(2.5, 1.0, 3.0) = " + ArrayAlg.clamp(2.5, 1.0, 3.0));
// 4. a class bound plus interface bounds: the class must come first
var archive = new Archive<Report>();
archive.store(new Report("Q3", 12));
archive.store(new Report("Q1", 30));
archive.store(new Report("Q2", 20));
System.out.println("archived in order: " + archive.sorted());
}
}
class Pair<T> {
private final T first;
private final T second;
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
}
class ArrayAlg {
/** Returns the smallest element, or null for an empty array. */
public static <T extends Comparable<T>> T min(T[] a) {
if (a == null || a.length == 0) return null;
T smallest = a[0];
for (int i = 1; i < a.length; i++)
if (smallest.compareTo(a[i]) > 0) smallest = a[i]; // OK: T has compareTo
return smallest;
}
/**
* Gets the minimum and maximum of an array of objects of type T.
* @param a an array of objects of type T
* @return a pair with the min and max values, or null if a is null or empty
*/
public static <T extends Comparable<? super T>> Pair<T> minmax(T[] a) {
if (a == null || a.length == 0) return null;
T min = a[0];
T max = a[0];
for (int i = 1; i < a.length; i++) {
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
/** Two bounds, separated by &. */
public static <T extends Number & Comparable<T>> T clamp(T value, T low, T high) {
if (value.compareTo(low) < 0) return low;
if (value.compareTo(high) > 0) return high;
return value;
}
}
class Stats<T extends Number> {
private final List<T> values;
Stats(List<T> values) { this.values = values; }
double average() {
double sum = 0;
for (T v : values) sum += v.doubleValue(); // OK: every T is a Number
return values.isEmpty() ? 0 : sum / values.size();
}
}
abstract class Document {
abstract String title();
}
class Report extends Document implements Comparable<Report>, Serializable {
private static final long serialVersionUID = 1L;
private final String title;
private final int pages;
Report(String title, int pages) { this.title = title; this.pages = pages; }
@Override String title() { return title; }
@Override public int compareTo(Report other) { return title.compareTo(other.title); }
@Override public String toString() { return title + "(" + pages + "p)"; }
}
/** One class bound (first), then any number of interface bounds. */
class Archive<T extends Document & Comparable<T> & Serializable> {
private final List<T> items = new ArrayList<>();
void store(T item) { items.add(item); }
List<String> sorted() {
var copy = new ArrayList<>(items);
Collections.sort(copy); // uses Comparable
var titles = new ArrayList<String>();
for (T t : copy) titles.add(t.title()); // uses Document
return titles;
}
}
min = 1996-01-23
max = 2023-09-19
smallest word: apple
smallest number: 7
empty array: null
average temperature 21.33, average count 5.00
clamp(15, 0, 10) = 10
clamp(2.5, 1.0, 3.0) = 2.5
archived in order: [Q1, Q2, Q3]
Common questions
Why does the keyword say extends when the bound is an interface?
In a bound, extends means "is a subtype of", which covers both classes and interfaces. The designers reused the existing keyword instead of introducing a new one. You never write implements in a type parameter.
What is the difference between <T extends Comparable<T>> and <T extends Comparable<? super T>>?
The first requires T to be comparable with exactly T. The second also accepts types that inherit their compareTo from a supertype, such as LocalDate, which is Comparable<ChronoLocalDate>. Library code should use the second form, as Collections.max and Collections.sort do.
Why can't I put the class bound after an interface bound?
The language requires the class (if there is one) to come first, mirroring class X extends C implements I, J. The first bound also determines the erasure of the type variable, so its position matters for the generated code.
Can a type variable have a bound that refers to itself?
Yes, and it's common. <T extends Comparable<T>> is a recursive bound. Enums use the same idea: Enum<E extends Enum<E>> guarantees that compareTo only compares constants of the same enum type.
Can I put bounds on wildcards and type variables in the same signature?
Yes. A signature like static <T extends Number> double sum(List<? extends T> values) is legal. In practice, choose one: either a bounded type variable when you need to name the type, or a bounded wildcard when you don't.
Summary
- An unbounded type variable only offers the methods of
Object. - A bound,
<T extends BoundingType>, restrictsTto subtypes of the bounding type and makes its methods available on values of typeT. extendsmeans "subtype of" and is used for both classes and interfaces.- Multiple bounds are separated by
&. Any number of interfaces, at most one class, and the class must come first. - Generic classes can be bounded too:
class Stats<T extends Number>. - Prefer
Comparable<T>over the rawComparable. For library code, use<T extends Comparable<? super T>>so that types likeLocalDatethat inheritcompareTofrom a supertype also work. - Bound violations are compile-time errors at the point of use.
Practice Questions
Why does <T> T max(T a, T b) { return a.compareTo(b) > 0 ? a : b; } not compile, and how do you fix it?
T is unbounded, so the compiler only knows Object's methods, and compareTo isn't one of them. Add a bound: <T extends Comparable<T>> T max(T a, T b).
Comparable is an interface. Why is the bound written T extends Comparable<T> and not T implements Comparable<T>?
In a bound, extends means "is a subtype of", for classes and interfaces alike. Java has no implements form for type variable bounds.
Which of these declarations are legal? (a) <T extends Runnable & Thread> (b) <T extends Thread & Runnable> (c) <T extends Runnable & AutoCloseable>
(b) and (c). In (a), the class Thread isn't the first bound, which is illegal. (c) has only interface bounds, which is fine.
Can you call Stats<T extends Number> with T = BigDecimal? With T = String?
BigDecimal extends Number, so Stats<BigDecimal> is fine. String isn't a Number, so Stats<String> is a compile-time error.
Why can't a method with bound <T extends Comparable<T>> return a LocalDate when called with a LocalDate[] array?
LocalDate implements Comparable<ChronoLocalDate>, not Comparable<LocalDate>. So T = LocalDate doesn't satisfy the bound, and the compiler can only choose T = ChronoLocalDate, which can't be assigned to LocalDate. The bound Comparable<? super T> fixes this.
Previous: Java Generics: Generic Classes and Generic Methods
Next: Java Type Erasure: Raw Types, Translation and Bridge Methods
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.