这串JAVA代码如何实现按科目成绩排序啊?

发布网友 发布时间:2022-04-26 01:21

我来回答

1个回答

热心网友 时间:2022-05-05 03:47

排序可以使用Collections.sort。

例子如下:

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Main { private static class Student{ private String name; private float grade; public Student(String name, float grade) { this.name = name; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getGrade() { return grade; } public void setGrade(float grade) { this.grade = grade; } @Override public String toString() { return name + " " + grade; } } public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Tom", 86)); students.add(new Student("Jack", 70)); students.add(new Student("Mary", 90)); Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (o1.getGrade() - o2.getGrade() > 0) { return 1; } else if (o1.getGrade() - o2.getGrade() < 0) { return -1; } else { return 0; } } }); for (Student student : students) { System.out.println(student.toString()); } }}

使用要排序的字段来比较。就可以得到有序的列表。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com