关于#数组排序#的问题,如何解决?

Student类定义如下,在测试类Sy3_4的主方法中,创建Student数组,表示一个班级的学生,随机给每个学生的成绩赋值(1-100之间),利用Arrays类的sort方法按学生成绩对学生排序,输出排序前和排序后的学生学号和学生成绩。参考输出结果如下。

提示:Arrays.sort(Student[] a, Comparaotr c);
可定义实现Comparator接口的类,重写compare方法(public int compare(Student a, Student b)),返回学生成绩的差值。
 class Student {
    String name;
    int id;
    int score;
    public Student() {}
    public Student(String s, int n, int a){
        name = s;
        id = n;
        score = a;
    }
    public void setName(String s) {
        name = s;
    }
    public void setScore(int a) {
        score = a;
    }
    public void setID(int n) {
        id = n;
    }
    public String getName() {
        return name;
    }
    public int getScore() {
        return score;
    }
    public int getID() {
        return id;
    }    
}

img

参考如下:

Arrays.sort(students, new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.score - o2.score;
    }
});

// 如果score变量是私有的,就用它的get方法【无论score是不是私有,都可】
Arrays.sort(students, new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getScore() - o2.getScore();
    }
});

如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!

按照成绩排序 , 成绩一样 学号小的靠前

class Student {
    String name;
    int id;
    int score;

    public Student() {
    }

    public Student(String s, int n, int a) {
        name = s;
        id = n;
        score = a;
    }

    public void setName(String s) {
        name = s;
    }

    public void setScore(int a) {
        score = a;
    }

    public void setID(int n) {
        id = n;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    public int getID() {
        return id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", score=" + score +
                '}';
    }

    public static void main(String[] args) {

        Student A = new Student("A", 10, 100);
        Student B = new Student("B", 6, 200);
        Student C = new Student("C", 20, 100);

        Student[] arr = new Student[]{A,B,C};
        System.out.println(Arrays.toString(arr));
        Arrays.sort(arr , (o1, o2) -> (o1.getScore() == o2.getScore()) ? (o1.getID() - o2.getID()) : (o1.getScore() - o2.getScore()));
        System.out.println(Arrays.toString(arr));
    }
}