How to implement a generic `max(Comparable a, Comparable b)` function in Java?

Viewed 12961

I'm trying to write a generic max function that takes two Comparables.

So far I have

public static <T extends Comparable<?>> T max(T a, T b) {
    if (a == null) {
        if (b == null) return a;
        else return b;
    }
    if (b == null)
        return a;
    return a.compareTo(b) > 0 ? a : b;
}

This fails to compiles with

The method compareTo(capture#5-of ?) in the type Comparable<capture#5-of ?> is not applicable for the arguments (T)

What I think this is saying is that that the ? in Comparable<?> may be interpreted as one type for parameter a, and another for parameter b, so that they can't be compared.

How do I dig myself out of this hole?

5 Answers

It's offten better getting already implemented iso create owns. See at Min / Max function with two Comparable. Simplest is org.apache.commons.lang.ObjectUtils:

Comparable<C> a = ...;
Comparable<C> b = ...;
Comparable<C> min = ObjectUtils.min(a, b);
Related