1.创建学生类
public class Student implements Comparable<Student> {
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student(String name, int chineseScore, int mathScore, int englishScore) {
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
// Getters
public String getName() {
return name;
}
public int getChineseScore() {
return chineseScore;
}
public int getMathScore() {
return mathScore;
}
public int getEnglishScore() {
return englishScore;
}
// Setters
public void setName(String name) {
this.name = name;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
@Override
public int compareTo(Student other) {
if (this.chineseScore != other.chineseScore) {
return Integer.compare(other.chineseScore, this.chineseScore);
}
if (this.mathScore != other.mathScore) {
return Integer.compare(other.mathScore, this.mathScore);
}
if (this.englishScore != other.englishScore) {
return Integer.compare(other.englishScore, this.englishScore);
}
return this.name.compareTo(other.name);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chineseScore=" + chineseScore +
", mathScore=" + mathScore +
", englishScore=" + englishScore +
'}';
}
}
2.main方法测试类
import java.util.*;
public class StudentTest {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 81, 90, 100),
new Student("Bob", 80, 90, 90),
new Student("Cob", 80, 90, 90),
new Student("Charlie", 80, 90, 100),
new Student("Dave", 70, 80, 90)
);
Collections.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
在Java中,Comparable
接口使对象能够相互比较。该接口定义了一个compareTo
方法,该方法用于指定对象排序的方式。在Student
类中,我们实现了这个接口并覆盖了compareTo
方法,用以定义学生对象(Student
对象)之间的排序规则。
在compareTo
方法中,我们首先比较学生的语文成绩。如果两个学生的语文成绩不同,则按成绩降序排列(得分高的排在前)。如果它们的语文成绩相同,我们则接着比较他们的数学成绩。如果数学成绩也相同,接下来比较英语成绩。如果所有的成绩都一样,最后根据学生姓名的字母顺序升序排列。
在确定了这个比较逻辑后,我们可以很容易地对一个包含Student
对象的集合进行排序。只需要调用Collections.sort()
方法,并传入我们的学生列表。然后Java的排序算法将使用我们定义的compareTo
方法为这些对象排序。排序的结果将使得列表根据指定的规则排列,即首先是语文成绩最高的学生,然后是数学成绩,接着是英语成绩,最后是姓名的字母顺序。