泛型 <T extends Comparable<?超级T>>在 collection.sort/可比较的代码中? [英] Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code?
问题描述
我一直使用类似的接口通过 collection.sort 为我的类提供自然排序.
I use comparable interface all the time to provided natural ordering for my class through collection.sort.
基本上如果我有一个person类,我会让它实现Comparable接口并提供compareTo的实现.但是在javadocs中Collections.sort的定义中,我看到了这个签名
Basically if I have a person class, I will get it to implement Comparable interface and will provide the implementation of compareTo. However in the definition of Collections.sort in javadocs, I see this signature
public static <T extends Comparable<? super T>> void sort(List<T> list)
我根本不明白这个泛型定义?不应该只是说
I don't understand this generics definition at all? Shouldn't it just say
<T implements Comparable<T>>
有人可以帮我解决这个问题吗?
Can someone help me with this?
推荐答案
其实就是说T 可以实现Comparable
,不仅仅是Comparable
.
Actually, it means that T can implement Comparable<? super T>
, not just Comparable<T>
.
例如,表示一个Student
类可以实现Comparable
,其中Student
是Person的子类代码>:
For example, it means that a Student
class can implement Comparable<Person>
, where Student
is a subclass of Person
:
public class Person {}
public class Student extends Person implements Comparable<Person> {
@Override public int compareTo(Person that) {
// ...
}
}
在这种情况下,列表可以通过 Collections.sort()
排序,但只能基于 Person
的属性,因为您传递了 Student
将 compareTo()
实例化为 Person
(当然,除非你向下转换它).
In this case, a List can be sorted by Collections.sort()
but only based on Person
's properties, because you pass the Student
instance into compareTo()
as a Person
(unless you downcast it, of course).
然而,在实践中,您永远不会看到 Student
类实现 Comparable
.那是因为 Person
可能已经实现了 Comparable
,而 Student
继承了它的实现.然而,最终结果是相同的:您可以将 List
传递给 Collections.sort()
并将其排序在 Person
's 属性.
In practice however, you'll never see a Student
class implement Comparable<Person>
. That's because Person
will probably have implemented Comparable<Person>
, and Student
inherits it implementation. The end result is the same however: you can pass a List<Student>
to Collections.sort()
and have it sorted on Person
's properties.
Comparable
和Comparable<的区别?super T>
在 Collections.sort() 的重载版本,它带有一个 Comparator
:
The difference between Comparable<T>
and Comparable<? super T>
is more obvious in the overloaded version of Collections.sort() that takes a 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());
这篇关于泛型 <T extends Comparable<?超级T>>在 collection.sort/可比较的代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!