JAVA中根据权重排序
时间: 2023-06-05 07:07:24 浏览: 217
可以使用Java中的Collections.sort()方法,并实现Comparator接口来设置排序规则。具体实现可以参考以下代码:
```
public class Example {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 80));
students.add(new Student("Jerry", 90));
students.add(new Student("Tony", 70));
students.add(new Student("Alice", 85));
Collections.sort(students, new Comparator<Student>() {
@Override
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;
}
}
```
输出结果为:
```
Jerry 90
Tom 80
Alice 85
Tony 70
```