Android list按照时间排序的问题

时间:2022-06-17 21:09:30

刚开始按照这种写法,对list进行时间排序:


private void sortByTimeRepoList(List<ReposInfo> itemInfoList, final int which) {
    Collections.sort(itemInfoList, new Comparator<ReposInfo>() {
                @Override
                public int compare(ReposInfo item1, ReposInfo item2) {
                    Date date1 = stringToDate(Miscellaneous.longToDate(item1.getMtime() * 1000));
                    Date date2 = stringToDate(Miscellaneous.longToDate(item2.getMtime() * 1000));
            // 对日期字段进行升序,如果欲降序可采用after方法
            if (which == mainActivity.SORT_ORDER_DESCENDING ? date1.before(date2) : date1.after(date2)) {//before是指时间从最新时间下降到之前
                return 1;
            }
            return -1;
                }
            }
    );
}


这种写法的时间排序刚开始没问题(因为开始测试的数据时间都不相同),后来发现,有item的时间相同时,会报错:

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


百度一番之后,大多数人都说是没有考虑  date1 == date2 这种情况,后来在*上看到有个大神的提示:

https://*.com/questions/10234038/compare-method-throw-exception-comparison-method-violates-its-general-contract

把代码改了一番:


private void sortByTimeRepoList(List<ReposInfo> itemInfoList, final int which) {
    Collections.sort(itemInfoList, new Comparator<ReposInfo>() {
                @Override
                public int compare(ReposInfo item1, ReposInfo item2) {
                    Date date1 = stringToDate(Miscellaneous.longToDate(item1.getMtime() * 1000));
                    Date date2 = stringToDate(Miscellaneous.longToDate(item2.getMtime() * 1000));


                    return which == mainActivity.SORT_ORDER_DESCENDING ? date2.compareTo(date1) : date1.compareTo(date2);
                }
            }
    );
}


再去测试,就OK了!

代码里的

which == mainActivity.SORT_ORDER_DESCENDING 

这一句代表的是升序或者降序,前面的date2.compareTo(date1)代表降序,后面的则是升序。