1.编写学生类Student,包含学号、姓名和成绩三个成员变量,设计成绩比较器,实现Comparator接口。编写测试类,使用Arrays类的带两个参数的sort方法对一组学生按成绩降序排序。(提示:随机产生100个学生对象)
时间: 2024-01-22 19:17:44 浏览: 67
下面是代码实现:
```java
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
public class 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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
}
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;
}
}
}
class Test {
public static void main(String[] args) {
Student[] students = new Student[100];
Random random = new Random();
for (int i = 0; i < students.length; i++) {
students[i] = new Student(i + 1, "Student" + (i + 1), random.nextInt(101));
}
System.out.println("排序前:");
for (Student student : students) {
System.out.println(student);
}
Arrays.sort(students, new ScoreComparator());
System.out.println("排序后:");
for (Student student : students) {
System.out.println(student);
}
}
}
```
运行结果:
```
排序前:
Student [id=1, name=Student1, score=96]
Student [id=2, name=Student2, score=29]
Student [id=3, name=Student3, score=9]
Student [id=4, name=Student4, score=15]
Student [id=5, name=Student5, score=63]
...
排序后:
Student [id=38, name=Student38, score=100]
Student [id=15, name=Student15, score=99]
Student [id=46, name=Student46, score=98]
Student [id=71, name=Student71, score=98]
Student [id=35, name=Student35, score=97]
...
```
阅读全文