Skip to lesson

Bounded types: <T extends …>

A bounded type parameter limits which types may be used for T, like <T extends Number>. In return, the Java compiler (javac) lets you call the bound's methods on T, such as doubleValue() or compareTo().

A plain T knows only Object's methods

An online store wants the higher of two values of any type that has an order. But inside <T> the Java compiler knows nothing about T, so it allows only the methods every object has: those of Object.

Example 1 · Without a bound, compareTo is unknown

NoBoundDemo.javaJava
public class NoBoundDemo {    static <T> T higher(T a, T b) {        if (a.compareTo(b) > 0) {            return a;        }        return b;    }
    public static void main(String[] args) {        System.out.println(higher(6000, 11000));    }}
Sample compiler output
NoBoundDemo.java:3: error: cannot find symbol
        if (a.compareTo(b) > 0) {
             ^
  symbol:   method compareTo(T)
  location: variable a of type T
  where T is a type-variable:
    T extends Object declared in method <T>higher(T,T)
1 error

What this code does

  • T could be any type, even one with no order, so the Java compiler checks a.compareTo(b) against Object only.
  • Object has no compareTo, hence "cannot find symbol ... location: variable a of type T". The fix comes in the third section.

This is the price of a plain T: it accepts every type, so it can promise only what every type has, such as equals, hashCode and toString. To call more, tell the Java compiler more about T.

Upper bound with a class: <T extends Number>

A bounded type parameter is a type parameter with a limit, written <T extends Bound>. Only the bound or its subtypes may be used for T, and inside the code T can use every method of the bound.

Write <T extends Number>, and only Number or its subclasses (Integer, Double, Long and more) may be used for T. In return, every T has the Number methods, such as doubleValue().

A bound works like a filter. <T extends Number> lets Integer, Double and Long through, because they are all Numbers, and inside the method T can call Number methods such as doubleValue(). String and Boolean are not Numbers, so the Java compiler refuses them with a compile error.

Example 2 · <T extends Number>: add up any kind of number

BillDemo.javaJava
public class BillDemo {    static <T extends Number> double total(T[] amounts) {        double sum = 0;        for (T amount : amounts) {            sum += amount.doubleValue();        }        return sum;    }
    public static void main(String[] args) {        Integer[] prices = { 6000, 2000, 500 };        Double[] fees = { 99.5, 49.5 };        Long[] points = { 1200L, 800L };
        System.out.println("Items: Rs. " + total(prices));        System.out.println("Fees: Rs. " + total(fees));        System.out.println("Reward points: " + total(points));    }}
Output
Items: Rs. 8500.0
Fees: Rs. 149.0
Reward points: 2000.0

What this code does

  • <T extends Number> lets total call amount.doubleValue(), because every Number has it.
  • One method adds Integer, Double and Long values, and the result is always a double, so 125.0 prints with .0.

Example 3 · A type outside the bound

BoundErrorDemo.javaJava
public class BoundErrorDemo {    static <T extends Number> double total(T[] amounts) {        double sum = 0;        for (T amount : amounts) {            sum += amount.doubleValue();        }        return sum;    }
    public static void main(String[] args) {        String[] products = { "Keyboard", "Camera" };        System.out.println(total(products));    }}
Sample compiler output
BoundErrorDemo.java:12: error: method total in class BoundErrorDemo cannot be applied to given types;
        System.out.println(total(products));
                           ^
  required: T[]
  found:    String[]
  reason: inference variable T has incompatible bounds
    upper bounds: Number
    lower bounds: String
  where T is a type-variable:
    T extends Number declared in method <T>total(T[])
1 error

What this code does

  • String is not a Number, so the Java compiler refuses the call before the program can run.
  • The reason lines show the clash: T would have to be String (lower bound), but must also be a Number (upper bound).

The word is always extends in a bound, and it means "is the bound or a subtype of it", as in The extends keyword (opens in a new tab). It covers Number itself too: total(new Number[] { 1, 2.5 }) also compiles.

Interface bounds: <T extends Comparable<T>>

Comparable<T> is a generic Java interface for types that have a natural order. Its one method, a.compareTo(b), returns a negative number, zero or a positive number when a is smaller than, equal to or bigger than b.

String, Integer and Double already implement Comparable. Bound T by it, and compareTo becomes legal inside the method. A bound always uses extends, even when the bound is an interface.

Example 4 · A generic max with Comparable

MaxDemo.javaJava
public class MaxDemo {    static <T extends Comparable<T>> T higher(T a, T b) {        if (a.compareTo(b) > 0) {            return a;        }        return b;    }
    static <T extends Comparable<T>> T max(T[] items) {        T best = items[0];        for (T item : items) {            if (item.compareTo(best) > 0) {                best = item;            }        }        return best;    }
    public static void main(String[] args) {        System.out.println("Higher price: " + higher(6000, 11000));        System.out.println("Later in A-Z: " + higher("Keyboard", "Camera"));        Double[] ratings = { 4.2, 4.8, 3.9 };        System.out.println("Best rating: " + max(ratings));    }}
Output
Higher price: 11000
Later in A-Z: Keyboard
Best rating: 4.8

What this code does

  • <T extends Comparable<T>> lets the code call a.compareTo(b): every such T promises that method.
  • Integer compares by value and String in dictionary (A-Z) order, so "Keyboard" beats "Camera".
  • max keeps the best item so far and replaces it whenever compareTo returns a positive number.

Example 5 · Your own class fits the bound

CostliestDemo.javaJava
class Product implements Comparable<Product> {    String name;    int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }
    public int compareTo(Product other) {        return Integer.compare(this.price, other.price);    }}
public class CostliestDemo {    static <T extends Comparable<T>> T max(T[] items) {        T best = items[0];        for (T item : items) {            if (item.compareTo(best) > 0) {                best = item;            }        }        return best;    }
    public static void main(String[] args) {        Product[] catalog = {            new Product("Headphones", 6000),            new Product("Monitor", 11000),            new Product("Keyboard", 2000)        };        Product top = max(catalog);        System.out.println("Costliest: " + top.name + ", Rs. " + top.price);    }}
Output
Costliest: Monitor, Rs. 11000

What this code does

  • implements Comparable<Product> gives Product a natural order: by price.
  • Integer.compare(x, y) returns a negative number, zero or a positive number, exactly what compareTo must return.
  • Now Product fits <T extends Comparable<T>>, so the same max works with no change.

Read <T extends Comparable<T>> as "a T that can be compared with another T". The Comparable (opens in a new tab) lesson in Sorting & Comparing uses the same interface to sort whole lists.

Multiple bounds and bounded generic classes

Multiple bounds make a type parameter meet several conditions at once, written with &: <T extends Number & Comparable<T>>. A class bound, if there is one, must come first, followed by any number of interfaces.

Sometimes T must be two things at once: a number you can add up and a value you can compare. Join the bounds with &. A generic class can carry bounds too, right after its name.

Example 6 · A bounded generic class with two bounds

StatsDemo.javaJava
class PriceStats<T extends Number & Comparable<T>> {    private T[] prices;
    PriceStats(T[] prices) {        this.prices = prices;    }
    T highest() {        T best = prices[0];        for (T p : prices) {            if (p.compareTo(best) > 0) {                best = p;            }        }        return best;    }
    double average() {        double sum = 0;        for (T p : prices) {            sum += p.doubleValue();        }        return sum / prices.length;    }}
public class StatsDemo {    public static void main(String[] args) {        Integer[] today = { 6000, 2000, 11000, 500 };        PriceStats<Integer> stats = new PriceStats<>(today);        System.out.println("Highest: Rs. " + stats.highest());        System.out.println("Average: Rs. " + stats.average());    }}
Output
Highest: Rs. 11000
Average: Rs. 4875.0

What this code does

  • T extends Number & Comparable<T>: T must be a Number (so doubleValue() works) and Comparable (so compareTo works). Integer is both.
  • The bound sits after the class name, so every method of PriceStats can use both kinds of method on T.
  • PriceStats<String> would not compile: String is comparable, but not a Number.

There is no <T super X> for a type parameter: bounds on T are upper bounds only. A lower limit, ? super, exists for wildcards, in Wildcards (opens in a new tab).

Find the bug

Find the bound bug

Each snippet should compile. Tap the wrong line, then check the fix.

A generic max for any comparable type.

Round 1 of 4

Next step

Check your understanding

12 quick questions