// 用户自己开发一个学生类,包括姓名\学号\成绩 三个属性,现在用户希望能使用// java.util.Arrays.sort()方法来根据学员成绩,排序一个学生类数组,请问要如何实现?//主要是要想到用Comparator来实现,熟悉api是关键
import java.util.Arrays; import java.util.Comparator; /** * The Class SortStudent. */ public class SortStudent { private static Student[] students = null; /** * The main method. * * @param args * the arguments */ public static void main(String[] args) { initData(); Arrays.sort(students, new ComparatorStudent()); for (int i = 0; i < students.length; i++) { System.out.println(students[i].toString()); } } private static void initData() { students = new Student[6]; students[0] = new Student("张三", 1, 87.0f); students[1] = new Student("李四", 3, 23); students[2] = new Student("王五", 4, 57.0f); students[3] = new Student("赵柳", 2, 187.0f); students[4] = new Student("小七", 6, 47.0f); students[5] = new Student("八哥", 8, 57.0f); } } /** * The Class ComparatorStudent. */ class ComparatorStudent implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { return (int) (o1.getScore() - o2.getScore()); } } /** * The Class Student. */ class Student { /** The name. */ private String name = null; /** The id. */ private int id = 0; /** The score. */ private double score = 0d; /** * Instantiates a new student. */ public Student() { } /** * Instantiates a new student. * * @param name * the name * @param id * the id * @param score * the score */ public Student(String name, int id, double score) { super(); this.name = name; this.id = id; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "name: " + this.name + " id: " + this.id + " score: " + this.score; } }相关资源:微信小程序源码-合集3.rar