用arraylist按成绩对类排序
时间: 2024-01-26 22:20:13 浏览: 21
以下是一个示例代码,可以按照成绩对 ArrayList 进行排序:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("John", 80));
students.add(new Student("Jane", 90));
students.add(new Student("Mary", 70));
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s2.getScore() - s1.getScore();
}
});
for (Student student : students) {
System.out.println(student.getName() + " (" + student.getScore() + ")");
}
}
}
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
在这个示例代码中,我们创建了一个 `Student` 类,它有一个 `name` 和 `score` 属性。我们创建了一个 `ArrayList`,并向其中添加了一些 `Student` 对象。
我们使用 `Collections.sort()` 方法对 `ArrayList` 进行排序。我们传递了一个 `Comparator` 对象,该对象定义了如何比较两个 `Student` 对象。在这个例子中,我们按照 `score` 属性进行比较。如果 `s2.getScore() - s1.getScore()` 返回负数,则 `s2` 小于 `s1`,如果返回正数,则 `s2` 大于 `s1`,如果返回零,则 `s2` 等于 `s1`。
最后,我们遍历排序后的 `ArrayList`,并输出每个 `Student` 对象的 `name` 和 `score` 属性。