记 某List.sort()后排序结果异常
背景:某次查看日志,发现数据不符合预期,希望获取的是降序排序,但是部分数据是乱序的
已知List.sort()方法应该不会出异常,所以应该是判断先后方法出问题了
果然,因为一开始写代码时,没有考虑到差值可能会超出int取值范围,由此导致排序异常
PS:差值超出int取值范围了
原代码
List<XXBean> xxxList = new ArrayList<>();
xxxList.sort((xXBean, xXBean1) -> {
long time1 = Long.parseLong(xXBean.getXXCreate());
long time2 = Long.parseLong(xXBean1.getXXCreate());
return (int) (time2 - time1);
});
if (xxxList.size() > 6) {
initDeleteList.addAll(xxxList.subList(6, xxxList.size()));
}
调整后:
List<XXBean> xxxList = new ArrayList<>();
xxxList.sort((xXBean, xXBean1) -> {
long time1 = Long.parseLong(xXBean.getXXCreate());
long time2 = Long.parseLong(xXBean1.getXXCreate());
return Long.compare(time2, time1);
});
if (xxxList.size() > 6) {
initDeleteList.addAll(xxxList.subList(6, xxxList.size()));
}