java 实现Comparable ,重写compareTo遇到的问题:排序用的属性值重复,则不会放入TreeSet的问题解决


public class TestObj implements Comparable<TestObj>{
    private long expireTime;//超时时间(业务中主要根据这个顺序排序)
    private String testValue;
    @Override
    public int compareTo(TestObj o) {
//        return Long.compare(expireTime, o.getExpireTime());
        //会出现多个超时时间相同的情况,直接用compare返回的结果值判断,会自动过滤掉相同超时时间的数据
        //所以,这里用了一个判断,超时时间相同,则根据testValue排序
        int result = 0;
        //按照超时时间顺序排序
        result = Long.compare(expireTime,o.getExpireTime());
        //如果超时时间相同 就对testValue进行比较并排序
        if(0 == result){
            result = testValue.compareTo(o.getTestValue());//对字符串进行顺序排序(返回字符串ASCII码之间差值)
        }
        return result;
    }

 

private TreeSet<TestObj> testObjSet = new TreeSet<>();

TestObj testObj = new TestObj();
testObj.setExpireTime(1590298923000);
testObj.setTestValue("ab");
testObj = new TestObj();
testObj.setExpireTime(1590298923002);
testObj.setTestValue("abc");
testObj = new TestObj();
testObj.setExpireTime(1590298923002);
testObj.setTestValue("ab");
testObj = new TestObj();
testObj.setExpireTime(1590298923003);
testObj.setTestValue("ab");

参考:

https://segmentfault.com/a/1190000005738975

相关文档:

https://www.iteye.com/blog/ocaicai-794438

https://blog.csdn.net/xtayfjpk/article/details/24806887

https://blog.csdn.net/loveyou388i/article/details/80134346?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

https://github.com/NeilRon/FreeTest/blob/master/src/main/java/xyz/neilron/freetest/TreeSetTest.java

https://blog.csdn.net/neilron/article/details/52834356?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.nonecase

https://blog.csdn.net/qq_36852780/article/details/92411080?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase

 

https://blog.csdn.net/chenfeng0104/article/details/83702618?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值