泛型<t extends =“”的解释<?=“”super =“”t =“”>&gt;在collection.sort /可比代码?</t>

时间:2014-09-11 04:37:47

标签: java generics

我一直使用类似的界面通过collection.sort为我的班级提供自然的顺序。

基本上如果我有一个人类,我会让它实现Comparable接口并提供compareTo的实现。但是在javadocs中Collections.sort的定义中,我看到了这个签名

public static <T extends Comparable<? super T>> void sort(List<T> list)

我根本不理解这个泛型定义?不应该只是说

<T implements Comparable<T>>

有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:38)

实际上,这意味着T 可以实施Comparable<? super T>,而不只是Comparable<T>

例如,这意味着Student类可以实现Comparable<Person>,其中StudentPerson的子类:

public class Person {}

public class Student extends Person implements Comparable<Person> {
    @Override public int compareTo(Person that) {
        // ...
    }
}

在这种情况下,列表可以按Collections.sort()排序,但仅基于Person的属性,因为您将Student实例传递到compareTo()作为Person(当然,除非你贬低它)。

但在实践中,您永远不会看到Student类工具Comparable<Person>。这是因为Person可能已经实现了Comparable<Person>,而Student继承了它的实现。最终结果是相同的:您可以将List<Student>传递给Collections.sort(),并将其排序在Person的属性中。

Comparable<T>Comparable<? super T>之间的差异在the overloaded version of Collections.sort() Comparator<? super T>中更为明显:<{1}}:

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());

答案 1 :(得分:6)

即使type参数实现了接口,也总是将 extends 与泛型通配符一起使用。

如果你看一个实现Comparable的类,你会发现它实际上(应该)实现Comparable<T>,其中T是类本身。

如果考虑传递给Comparable接口的类型参数以及它在compareTo()方法中的使用方式,这是有意义的。

正如PM 77-1雄辩地指出的那样, super 关键字允许类,T或其父类之一实现Comparable