java定义一个含学生学号、姓名和成绩的类Student,进行升序排列并输出排序后的结果。
时间: 2024-05-14 16:14:13 浏览: 89
以下是Java代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Student {
private String id; // 学号
private String name; // 姓名
private double score; // 成绩
public Student(String id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("1001", "张三", 89.5));
students.add(new Student("1002", "李四", 78.5));
students.add(new Student("1003", "王五", 92.0));
students.add(new Student("1004", "赵六", 85.5));
Collections.sort(students, new Comparator<Student>() {
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;
}
});
for (Student s : students) {
System.out.println(s.getId() + " " + s.getName() + " " + s.getScore());
}
}
}
```
运行结果:
```
1002 李四 78.5
1004 赵六 85.5
1001 张三 89.5
1003 王五 92.0
```
阅读全文