I was going through Java Generics and understanding type parameter bounds. In the below code, I'm unable to figure why the compiler reports an error for line 38 but not 41.
If I change the type parameter bounds of the sort() method to <T extends Comparable<? super T>>
, then both of the invocations work.
import java.util.Collections;
import java.util.List;
class Person implements Comparable<Person> {
@Override
public int compareTo(Person o) {
return 0;
}
}
class Student extends Person {}
/* ------------------------------------------ */
class Player<T extends Player<T>> implements Comparable<T> {
@Override
public int compareTo(T o) {
return 0;
}
}
class Goalkeeper extends Player<Goalkeeper> {
@Override
public int compareTo(Goalkeeper o) {
return 1;
}
}
/* ------------------------------------------ */
public class ComparableTest {
private static <T extends Comparable<T>> void sort(List<T> list) {
list.sort(null);
}
public static void main(String[] args) {
List<Student> students = Collections.emptyList();
//! sort(students); // inferred type does not conform to equality constraint(s)
List<Goalkeeper> goalkeepers = Collections.emptyList();
sort(goalkeepers); // why ok?
}
}
students
is a List<Student>
, so with sort(List<T> list)
that means that T
is Student
.
However, Student
doesn't implement Comparable<Student>
, so the constraint <T extends Comparable<T>>
is violated.
goalkeepers
is a List<Goalkeeper>
, so T
is Goalkeeper
, and Goalkeeper
does implement Comparable<Goalkeeper>
, so all it good.