generics的解释<T extends Comparable > in collection.sort /可比代码?

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

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

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

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

 <T implements Comparable> 

有人可以帮我弄这个吗?

实际上,这意味着T 可以实现Comparable Comparable ,而不仅仅是Comparable

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

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

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

然而,在实践中,您永远不会看到Student类实现Comparable 。 那是因为Person可能已经实现了Comparable ,而Studentinheritance了它的实现。 最终结果是相同的:您可以将List传递给Collections.sort()并将其按Person的属性进行排序。

ComparableComparable之间的区别Comparable Comparable在Collections.sort()的重载版本中更明显,它带有一个Comparator Comparator

 class ByAgeAscending implements Comparator { @Override public int compare(Person a, Person b) { return a.getAge() < b.getAge(); } } List students = getSomeStudents(); Collections.sort(students, new ByAgeAscending()); 

即使type参数实现了接口,也始终使用带有generics通配符的extends

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

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

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