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://github.com/NeilRon/FreeTest/blob/master/src/main/java/xyz/neilron/freetest/TreeSetTest.java