Task 5 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 — algorithms over any comparable type

Lesson

One algorithm, every ordered type

With a Comparable bound, the array algorithms you already know — max, min, counting, searching — can be written once and reused for every ordered type. Instead of > (which only works on numbers), compare with compareTo(...) > 0.


Worked example

public static <T extends Comparable<T>> int countGreater(T[] arr, T threshold) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i].compareTo(threshold) > 0) {   // strictly greater
            count++;
        }
    }
    return count;
}

Integer[] nums = {3, 9, 2, 7};
System.out.println(countGreater(nums, 5));            // 2 — the 9 and the 7
String[] words = {"pear", "apple", "fig"};
System.out.println(countGreater(words, "banana"));    // 2 — pear and fig

The very same method counts numbers above 5 and words after "banana" alphabetically.


▶ Try it: run this — one algorithm, numeric order and alphabetical order.



Inside a generic method, replace a > b with...


For Strings, compareTo orders values...


Type exactly what this program prints.

class U {
    public static <T extends Comparable<T>> int cg(T[] arr, T t) {
        int c = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].compareTo(t) > 0) { c++; }
        }
        return c;
    }
}
public class Main { public static void main(String[] a){
    Integer[] n = {2, 8, 5, 9};
    System.out.println(U.cg(n, 5));
}}

Why does countGreater work for both Integers and Strings?


True or false?