其实,这表示T 可以 实现
Comparable<? super T>,而不仅仅是
Comparable<T>。
例如,这意味着一个
Student类可以实现
Comparable<Person>,其中
Student是的子类
Person:
public class Person {}public class Student extends Person implements Comparable<Person> { @Override public int compareTo(Person that) { // ... }}在这种情况下,可以按List进行排序,
Collections.sort()但只能基于
Person的属性进行排序,因为您将
Student实例
compareTo()作为传入
Person(当然,除非您向下转换)。
但是在实践中,您永远不会看到
Student类实现
Comparable<Person>。那是因为
Person可能已经实现了
Comparable<Person>,并且
Student继承了它的实现。但是,最终结果是相同的:您可以将传递给
List<Student>,
Collections.sort()并对其进行排序
Person。
之间的差
Comparable<T>和
Comparable<? superT>在更明显重载的版本Collections.sort()的,需要一个
Comparator<? super T>:
class ByAgeAscending implements Comparator<Person> { @Override public int compare(Person a, Person b) { return a.getAge() < b.getAge(); }}List<Student> students = getSomeStudents();Collections.sort(students, new ByAgeAscending());


