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

For best results you should use public static <T extends Comparable<? super T>> T max(T a, T b).

The problem with <T extends Comparable<?>> is that this says that the type T is comparable to some type, but you don't know what that type is. Of course, common sense would dictate that a class which implements Comparable should be able to be comparable to at least itself (i.e. be able to compare to objects of its own type), but there is technically nothing preventing class A from implementing Comparable<B>, where A and B have nothing to do with each other. <T extends Comparable<T>> solves this problem.

But there's a subtle problem with that. Suppose class X implements Comparable<X>, and I have a class Y that extends X. So class Y automatically implements Comparable<X> by inheritance. Class Y can't also implement Comparable<Y> because a class cannot implement an interface twice with different type parameters. This is not really a problem, since instances of Y are instances of X, so Y is comparable to all instances of Y. But the problem is that you cannot use the type Y with your <T extends Comparable<T>> T max(T a, T b) function, because Y doesn't implement Comparable<Y>. The bounds are too strict. <T extends Comparable<? super T>> fixes the problem, because it is sufficient for T to be comparable to some supertype of T (which would include all T instances). Recall the rule PECS - producer extends, consumer super - in this case, Comparable is a consumer (it takes in an object to compare against), so super makes sense.

This is the type bounds used by all of the sorting and ordering functions in the Java library.


You get this error because Comparable<?> basically says that it is comparable to something without any specifics. You should write Comparable<T> instead, so the compiler would know that type T is comparable to itself.