用Comparator接口自定义排序

求一个班级成绩的平均值和成绩排名(要名次和姓名),姓名用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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值