我正在阅读Java Generics并了解类型参数边界。在下面的代码中,我无法确定编译器报告第38行但不是41的错误的原因。
如果我将sort()方法的类型参数边界更改为<T extends Comparable<? super T>>
,则两个调用都会起作用。
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?
}
}
答案 0 :(得分:2)
students
是List<Student>
,因此sort(List<T> list)
表示T
为Student
。
但是,Student
并未实施Comparable<Student>
,因此违反了约束<T extends Comparable<T>>
。
goalkeepers
是List<Goalkeeper>
,因此T
为Goalkeeper
,Goalkeeper
实施Comparable<Goalkeeper>
,一切都很好。