欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

总成绩的集合排序

程序员文章站 2022-07-12 20:51:33
...

总成绩的集合排序
实体类

public class Student {
    private String name;//姓名
    private Integer che;//语文成绩
    private Integer ma;//数学成绩
    private Integer eng;//英语成绩

    public Student() {
    }

    public Student(String name, Integer che, Integer ma, Integer eng) {
        this.name = name;
        this.che = che;
        this.ma = ma;
        this.eng = eng;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getChe() {
        return che;
    }

    public void setChe(Integer che) {
        this.che = che;
    }

    public Integer getMa() {
        return ma;
    }

    public void setMa(Integer ma) {
        this.ma = ma;
    }

    public Integer getEng() {
        return eng;
    }

    public void setEng(Integer eng) {
        this.eng = eng;
    }

    /**
     * 这里计算总分
     * @return 总分
     */
    public Integer getSum(){
        return che+ma+eng;
    }
}

排序类

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        if(s1.getSum()<s2.getSum()){
            return 1;
        }else if (s1.getSum()>s2.getSum()){
            return -1;
        }else {
            return 0;
        }
    }
}

测试类

public class StudentTest {
    public static void main(String[] args) {
        TreeSet<Student> t=new TreeSet<>(new StudentComparator());//这里就没有用键盘输入了
        Student s1=new Student("张三",1,2,3);
        Student s2=new Student("李四",7,8,9);
        Student s3=new Student("王五",4,5,6);
        t.add(s1);
        t.add(s2);
        t.add(s3);
        for (Student s:t){//遍历
            System.out.println("姓名:"+s.getName()+"  ,总分:"+s.getSum());
        }
    }
}

输入结果
总成绩的集合排序