发布网友 发布时间: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()); } }}
使用要排序的字段来比较。就可以得到有序的列表。