As per Java API spec, the signature of Collections.reverseOrder is
public static <T> Comparator<T> reverseOrder()
And the example given in the method description says it needs to be used as
Arrays.sort(a, Collections.reverseOrder());
When we call the method, nowhere do we specify what type to use (what T resolves to).
How does the compiler resolve T in this case? Can the return type (T) be resolved based on the type of the object it is being assigned to?
Btw, I'm aware of the overloaded reverseOrder(Comparator<T> c)
method.
Arrays.sort() knows what kind of Comparator it needs, since T
is specified by the first argument (a
):
public static <T> void sort(T[] a, Comparator<? super T> c)
EDIT:
@Louis Wasserman correctly points out that we only need a Comparator<? super T>
, not a Comparator<T>
. Since Object
is a superclass of any T
, then Comparator<Object>
(the default if no generic parameters are given) is sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With