Bounded types: <T extends …>
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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 errorWhat this code does
Tcould be any type, even one with no order, so the Java compiler checksa.compareTo(b)againstObjectonly.Objecthas nocompareTo, 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().
Example 2 · <T extends Number>: add up any kind of number
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)); }}Items: Rs. 8500.0 Fees: Rs. 149.0 Reward points: 2000.0
What this code does
<T extends Number>letstotalcallamount.doubleValue(), because everyNumberhas it.- One method adds
Integer,DoubleandLongvalues, and the result is always adouble, so125.0prints with.0.
Example 3 · A type outside the bound
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)); }}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 errorWhat this code does
Stringis not aNumber, so the Java compiler refuses the call before the program can run.- The reason lines show the clash:
Twould have to beString(lower bound), but must also be aNumber(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
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)); }}Higher price: 11000 Later in A-Z: Keyboard Best rating: 4.8
What this code does
<T extends Comparable<T>>lets the code calla.compareTo(b): every suchTpromises that method.Integercompares by value andStringin dictionary (A-Z) order, so"Keyboard"beats"Camera".maxkeeps the best item so far and replaces it whenevercompareToreturns a positive number.
Example 5 · Your own class fits the bound
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); }}Costliest: Monitor, Rs. 11000
What this code does
implements Comparable<Product>givesProducta natural order: by price.Integer.compare(x, y)returns a negative number, zero or a positive number, exactly whatcompareTomust return.- Now
Productfits<T extends Comparable<T>>, so the samemaxworks 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
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()); }}Highest: Rs. 11000 Average: Rs. 4875.0
What this code does
T extends Number & Comparable<T>:Tmust be aNumber(sodoubleValue()works) andComparable(socompareToworks).Integeris both.- The bound sits after the class name, so every method of
PriceStatscan use both kinds of method onT. PriceStats<String>would not compile:Stringis comparable, but not aNumber.
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 4Next step
Check your understanding
12 quick questions