1

Inside java.util.Collections we have the below method signature

public static <T> void sort(List<T> list, Comparator<? super T> c) 

I don't understand why one would specify

Comparator<? super T>

instead of

Comparator<T>

Which use cases does it cover?

Bogdan T.
  • 668
  • 6
  • 13
  • Generics `PECS` rule – Hearen Aug 04 '18 at 04:32
  • Why wouldn't it be specified that way? If `S` is a supertype of `T`, then a `Comparator` does just fine for comparing `T` objects - and this signature reflects that. – Dawood ibn Kareem Aug 04 '18 at 04:33
  • Are you aware that `List` is not a subtype of `List`, such that `sort(subclassList, superclassComparator)` would not type-check if the method signature required the `List` and the `Comparator` to have the same type argument? (That is: are you asking a technical question, looking for a line of code enabled by this signature, or a design question, asking why that line of code is worth enabling?) – ruakh Aug 04 '18 at 04:41

1 Answers1

1

Here is an example:

class Person {}

class Student extends Person {}

? super T means ? is a superclass (or interface) of T. That is, if a comparator is Comparator<Person>, since Student is inherited from Person, this comparator should still work on Student.

List<Student> students = ...
Collections.sort(students, new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        // compare person
        return 0;
    }
});

If we change Comparator<? super T> to Comparator<T>, the above code will not compile.

zhh
  • 2,346
  • 1
  • 11
  • 22