踩坑日记之List.sort()排序抛出异常Comparison method violates its general contract!

场景 -> 从SVN上获取所有项目的tag记录然后按更新时间排序:

1 List<SVNDirEntry> list = new  ArrayList<SVNDirEntry>(entries);
2 List<SVNDirEntry> list2 = list.stream().sorted(Comparator.comparing(SVNDirEntry::getDate).reversed()).limit(15).collect(Collectors.toList());
3 list.sort((a1, a2) -> (int)(a1.getDate().getTime() - a2.getDate().getTime()));

意思是a1对象的更新时间大于a2的更新时间时不交换o1,o2的顺序,否则交换顺序,然后抛出异常:

java.lang.IllegalArgumentException: Comparison method violates its general contract!

查阅资料后知道了JDK7之后更换了新的排序算法TimSort(此处使用JDK8),没有对两值相等时的判定,直接当作1处理,因此报该异常。

解决方案:重写排序规则,加上两值相等的方案

1 private static class SVNTimeComparator implements Comparator<SVNDirEntry> {
2 
3         public int compare(SVNDirEntry b1, SVNDirEntry b2) {
4 
5             return b1.getDate().compareTo(b2.getDate());
6         }
7     }

原list排序改为: SVNTimeComparator comparator = new SVNTimeComparator(); list.sort(comparator); 

 

posted @ 2020-11-20 18:03  空指针终结者  阅读(824)  评论(0)    收藏  举报