Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Collections.reverseOrder know what type parameter to use while returning Comparator<T>

Tags:

java

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.

like image 784
Jagat Avatar asked Mar 22 '12 18:03

Jagat


1 Answers

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.

like image 101
Brendan Long Avatar answered Oct 07 '22 02:10

Brendan Long