Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.2 Generic methods — bounded type parameters

Lesson

Promising what T can do

A plain <T> could be any type, so the compiler only lets you use methods every object has (like equals and toString). Try to call compareTo on a plain T and you get a compile error: cannot find symbol. A bound fixes this: <T extends Comparable<T>> restricts T to types that can be compared — and now compareTo is allowed.


Worked example

public static <T extends Comparable<T>> T max(T[] arr) {
    T best = arr[0];
    for (int i = 1; i < arr.length; i++) {
        if (arr[i].compareTo(best) > 0) {   // allowed thanks to the bound
            best = arr[i];
        }
    }
    return best;
}

compareTo returns a negative number if the value is smaller, 0 if equal, and a positive number if larger. Note the keyword is extends even for an interface bound.


▶ Try it: run this — the same max works for Integers (numeric order) and Strings (alphabetical order).



Calling compareTo on a plain, unbounded T gives...


a.compareTo(b) returns a positive number when...


Type exactly what this program prints.

class U {
    public static <T extends Comparable<T>> T max(T[] arr) {
        T b = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i].compareTo(b) > 0) { b = arr[i]; }
        }
        return b;
    }
}
public class Main { public static void main(String[] a){
    Integer[] n = {4, 11, 7};
    System.out.println(U.max(n));
}}

Match each compareTo result to its meaning.


True or false?