关于TreeSet使用Comparable接口(基础)(练习)

需求

package com.TreeSet排序案例01;

import java.util.TreeSet;

public class main {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<Student>();
        Student s1 = new Student("aa",90,58);
        Student s2 = new Student("bb",60,45);
        Student s3 = new Student("cc",58,25);
        Student s4 = new Student("cc",16,37);
        Student s5 = new Student("dd",35,96);
        Student s6 = new Student("ee",25,45);
        Student s7 = new Student("ff",45,25);
        Student s8 = new Student("gg",45,25);
        Student s9 = new Student("hh",60,10);
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        ts.add(s7);
        ts.add(s8);
        ts.add(s9);
        for (Student s : ts) {
            System.out.println(s.getName() + ",语文:" + s.getChinese() + ",数学:" + s.getMath() + ",总分:" + s.getSum());
        }
    }
}

有参构造中的Sum = chinese+math;不要忘了加

package com.TreeSet排序案例01;

public class Student implements Comparable<Student> {

    private String name;
    private int Chinese;
    private int Math;
    private int Sum;

    public Student() {
    }

    public Student(String name, int chinese, int math) {
        this.name = name;
        Chinese = chinese;
        Math = math;
        Sum = chinese+math;
    }

    public int getSum() {
        return Sum;
    }

    public void setSum(int chinese, int math) {
        Sum = chinese + math;
    }

    public String getName() {
        return name;
    }

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

    public int getChinese() {
        return Chinese;
    }

    public void setChinese(int chinese) {
        Chinese = chinese;
    }

    public int getMath() {
        return Math;
    }

    public void setMath(int math) {
        Math = math;
    }

    @Override
    public int compareTo(Student o) {
        int i = this.Sum - (o.Math + o.Chinese);
        int i1 = i == 0 ? o.name.compareTo(this.name):i;
        return i1;
    }
}

输出结果为:
cc,语文:16,数学:37,总分:53
hh,语文:60,数学:10,总分:70
gg,语文:45,数学:25,总分:70
ff,语文:45,数学:25,总分:70
ee,语文:25,数学:45,总分:70
cc,语文:58,数学:25,总分:83
bb,语文:60,数学:45,总分:105
dd,语文:35,数学:96,总分:131
aa,语文:90,数学:58,总分:148

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值