用java编写学生类Student,包含学号、姓名和成绩三个成员变量,设计成绩比较器,实现Comparator接口。编写测试类,使用Arrays类的带两个参数的sort方法对一组学生按成绩降序排序。(提示:随机产生100个学生对象)
时间: 2024-01-22 10:18:59 浏览: 38
以下是Java代码实现:
```java
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
public class Student implements Comparator<Student> {
private int id;
private String name;
private int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
// 实现Comparator接口的compare方法,按成绩降序排序
@Override
public int compare(Student s1, Student s2) {
return s2.getScore() - s1.getScore();
}
public static void main(String[] args) {
Random random = new Random();
Student[] students = new Student[100];
for (int i = 0; i < 100; i++) {
int id = i + 1;
String name = "student" + id;
int score = random.nextInt(101);
students[i] = new Student(id, name, score);
}
System.out.println("排序前:");
for (Student student : students) {
System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getScore());
}
// 使用Arrays类的sort方法对学生按成绩降序排序
Arrays.sort(students, new Student());
System.out.println("\n排序后:");
for (Student student : students) {
System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getScore());
}
}
}
```
运行结果:
```
排序前:
1 student1 31
2 student2 68
3 student3 43
4 student4 12
5 student5 48
6 student6 74
7 student7 58
8 student8 97
9 student9 64
10 student10 75
...
排序后:
8 student8 97
41 student41 96
69 student69 94
16 student16 93
90 student90 92
71 student71 90
84 student84 90
21 student21 88
81 student81 88
40 student40 87
...
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)