Java泛型 - 推断类型不符合等式约束

时间:2018-03-22 06:23:14

标签: java generics contravariance

我正在阅读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?
    }
}

1 个答案:

答案 0 :(得分:2)

studentsList<Student>,因此sort(List<T> list)表示TStudent

但是,Student并未实施Comparable<Student>,因此违反了约束<T extends Comparable<T>>

goalkeepersList<Goalkeeper>,因此TGoalkeeperGoalkeeper 实施Comparable<Goalkeeper>,一切都很好。