我一直使用类似的界面通过collection.sort为我的班级提供自然顺序.
基本上如果我有一个人类,我会得到它来实现Comparable接口,并将提供compareTo的实现.但是在javadocs中Collections.sort的定义中,我看到了这个签名
public static <T extends Comparable<? super T>> void sort(List<T> list)
我根本不理解这个泛型定义?不应该只是说
<T implements Comparable<T>>
有人可以帮我弄这个吗?
Jan*_*sch 43
实际上,这意味着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()作为a 传递Person(当然,除非您将其向下传播).
然而,在实践中,您永远不会看到Student类实现Comparable<Person>.那是因为Person可能已经实现了Comparable<Person>,并Student继承了它的实现.最终的结果却是一样的:你可以传递List<Student>到Collections.sort()并将其分类上Person的属性.
之间的差Comparable<T>和Comparable<? super T>在更明显重载的版本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());
即使type参数实现了接口,也始终使用带有泛型通配符的extends.
如果你看一个实现Comparable的类,你会看到它实际上(应该)实现Comparable<T>,其中T是类本身.
如果考虑传递给Comparable接口的类型参数以及它在compareTo()方法中的使用方式,这是有意义的.
正如PM 77-1雄辩地指出的那样,super关键字允许类,T或其父类之一实现Comparable.
| 归档时间: | 
 | 
| 查看次数: | 16001 次 | 
| 最近记录: |