Chaz32621 Chaz32621 - 3 months ago 16
Java Question

Modifying a method so the arguments can be any type that implements Comparable

I would like to modify the following method so its arguments can be of any type that implements the

Comparable
interface. The method’s return type should be the same as the type of its parameter variables.

public static int max(int a, int b) {
if (a >b)
return a;
else
return b;
}


So in modifying it, I could just use
<T extends Comparable<T>>
, but how would I go about making the return types the same?

Answer

You essentially want something like this:

public static <T extends Comparable<T>> T max(T a, T b) {
    int n = a.compareTo(b);
    if (n > 0)
        return a;
    if (n < 0)
        return b;
    return a;
}

You can of course simplify this to the following (thank you to @pickypg for the notice):

public static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) < 1 ? b : a;
}