业务解决
2025/12/3小于 1 分钟
有一个学生类,按分数排序,再按学号排序如何实现?
方法1:实现 Comparable(最推荐)
public class Student implements Comparable<Student> {
private int id;
private int score;
@Override
public int compareTo(Student o) {
int r = Integer.compare(o.score, this.score); // 分数降序
return r != 0 ? r : Integer.compare(this.id, o.id); // 学号升序
}
}方法2:Comparator(不改类时使用)
Collections.sort(list,
(a, b) -> a.score != b.score ?
Integer.compare(b.score, a.score) :
Integer.compare(a.id, b.id)
);