定义一个Student类,其中含有成员变量stuId学号、name姓名、department系别及score成绩; 若想对Student类的多个对象进行以stuId或者department及score等为依据进行三种不同的排序,如何实现? 并写出代码来验证。
时间: 2024-03-11 22:47:34 浏览: 66
要对Student类的多个对象进行不同的排序,可以使用Java中的Comparator接口和Comparable接口实现。
首先,定义Student类,实现Comparable接口,用于stuId排序:
```java
public class Student implements Comparable<Student> {
private String stuId;
private String name;
private String department;
private double score;
// 构造函数
public Student(String stuId, String name, String department, double score) {
this.stuId = stuId;
this.name = name;
this.department = department;
this.score = score;
}
// 实现Comparable接口的compareTo方法,用于stuId排序
@Override
public int compareTo(Student other) {
return this.stuId.compareTo(other.stuId);
}
// getter和setter方法
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
```
接着,定义三个Comparator接口实现类,分别用于不同的排序方式:
```java
public class StuIdComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getStuId().compareTo(s2.getStuId());
}
}
public class DepartmentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getDepartment().compareTo(s2.getDepartment());
}
}
public class ScoreComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.getScore() > s2.getScore()) {
return 1;
} else if (s1.getScore() < s2.getScore()) {
return -1;
} else {
return 0;
}
}
}
```
最后,使用Collections类的sort方法对Student对象进行排序:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("1001", "张三", "计算机科学与技术", 85.5));
students.add(new Student("1002", "李四", "软件工程", 92.0));
students.add(new Student("1003", "王五", "信息与通信工程", 80.0));
// 按stuId排序
Collections.sort(students);
// 按department排序
Collections.sort(students, new DepartmentComparator());
// 按score排序
Collections.sort(students, new ScoreComparator());
// 输出排序结果
for (Student s : students) {
System.out.println(s.getStuId() + " " + s.getName() + " " + s.getDepartment() + " " + s.getScore());
}
}
}
```
在测试代码中,我们创建了一个Student列表,包含三个Student对象,分别按照stuId、department和score进行排序,并输出排序结果。
阅读全文