栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

通用说明 >在collection.sort /类似代码中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通用说明 >在collection.sort /类似代码中?

其实,这表示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());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495611.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号