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

我可以在不实现Comparable的情况下使用Comparator吗?

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

我可以在不实现Comparable的情况下使用Comparator吗?

你不用

Comparable
。您使用
Comparator

Comparable
是由对象实现的接口,用于指定它们与相同类型的其他对象的排序顺序。

Comparator
是一个通用接口,只需要两个对象并告诉您它们的排序顺序。因此,您可以执行以下操作:

public class Student {  private final int id;  private final String name;  private final int age;  public Student(int id, String name, int age) {    this.id = id;    this.name = name;    this.age = age;  }  public int getId() { return id; }  public String getName() { return name; }  public int getAge() { return age; }}

与:

public class AgeComparator implements Comparator<Student> {  public int compare(Student s1, Student s2) {    if (s1.getAge() == s2.getAge()) {      return 0;    } else {      return s1.getAge() < s2.getAge() ? -1 : 1;  }}

和:

List<Student> students = new ArrayList<Student>();students.add(new Student(1, "bob", 15));students.add(new Student(2, "Jane", 14));students.add(new Student(3, "Gary", 16));SortedSet<Student> set1 = new TreeSet<Student>(new AgeComparator());set1.addAll(students);for (Student student : set1) {  // age order}


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

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

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