用Comparator接口自定义排序

时间:2023-01-02 08:32:09

求一个班级成绩的平均值和成绩排名(要名次和姓名),姓名用ABC表示。例:第1名:C 100.


import java.util.*;
public class Test {
    public static void main(String[] args) {
        int[] score = {90,80,70,60,65,75,85,95,100,55,58,61,71,74,76,81,88,92,99,97};
        String[] name = new String[20];
        for(int i = 0; i < score.length; i++){
            name[i] = String.valueOf((char)('A' + i));
        }
        //存入list用于排序
        List<Student> list = new LinkedList<Student>();
        int sumScore = 0;
        for(int i = 0; i < score.length; i++){
            list.add(new Student(name[i], score[i]));
            sumScore += list.get(i).getScore();
        }
        System.out.println("全班平均分为:" + 1.0*sumScore/list.size());
        Collections.sort(list, new MyComp());
        for(int i = 0; i < list.size(); i++){
            System.out.println("第" + (i+1) + "名:" + list.get(i).getName() + " " + list.get(i).getScore());
        }

    }
}

//学生类
class Student{
    private int score;
    private String name;
    public Student(String name, int score){
        this.score = score;
        this.name = name;
    }

    public int getScore(){
        return score;
    }

    public String getName(){
        return name;
    }
}

//自定义排序
class MyComp implements Comparator<Student>{
    public int compare(Student o1, Student o2){
        if(o1.getScore() < o2.getScore()) return 1; //分数低的排后面
        if(o1.getScore() == o2.getScore()) return 0;
        return -1;
    }
}