java关于自定义的comparable排序

  1. 调用方法的对象和参数对象比较
  2. 如果返回0,代表两个对象相等。返回负数,代表调用方法的对象小,参数对象的大(升序)。
  3. 返回正数,代表调用方法的对象大,参数对象小(降序)。
  4. 理解不了,直接把规律记住就行了(点一下试一试)

    @Override
    public int compareTo(Student stu) {
        int result = (int) Math.ceil(this.getScope() - stu.getScope());
        result = result == 0 ? this.getAge().compareTo(stu.getAge()) : result;
        result = result == 0 ? this.getName().compareTo(stu.getName()) : result;

        System.out.println(this + "\t在和传入的对象\t" + stu + "比较" + "\t结果为:" + result);
        System.out.println("========================");
        return result;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", scope=" + scope +
                ", age=" + age +
                '}';
    }
public class TestOne {
    public static void main(String[] args) {
        TreeSet<Student> set = new TreeSet<>();
        set.add(new Student("liusan",90.0,20));
        set.add(new Student("lisi",90.0,20));
        set.add(new Student("wangwu",99.0,22));
        set.add(new Student("sunliu",100.0,22));
        System.out.println("========================");
        for (Student student : set) {
            System.out.println(student);
        }
    }
}
Student{name='liusan', scope=90.0, age=20}	在和传入的对象	Student{name='liusan', scope=90.0, age=20}比较	结果为:0
========================
Student{name='lisi', scope=90.0, age=20}	在和传入的对象	Student{name='liusan', scope=90.0, age=20}比较	结果为:-2
========================
Student{name='wangwu', scope=99.0, age=22}	在和传入的对象	Student{name='liusan', scope=90.0, age=20}比较	结果为:9
========================
Student{name='sunliu', scope=100.0, age=22}	在和传入的对象	Student{name='liusan', scope=90.0, age=20}比较	结果为:10
========================
Student{name='sunliu', scope=100.0, age=22}	在和传入的对象	Student{name='wangwu', scope=99.0, age=22}比较	结果为:1
========================
========================
Student{name='lisi', scope=90.0, age=20}
Student{name='liusan', scope=90.0, age=20}
Student{name='wangwu', scope=99.0, age=22}
Student{name='sunliu', scope=100.0, age=22}

总结一波

想要升序就用this减去传入来的对象。this.getScope() - stu.getScope
想要降序就用传入来的对象减去this。stu.getScope() -this.getScope

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值