简体   繁体   English

Java中的集合排序问题

[英]Collections Sort Issue in Java

To put it simply, I have a list of weeks ArrayList<Week> , each of which contains a list of days ArrayList<Day> , each of which contains a Date object within the Day class. 简单来说,我有一个星期列表ArrayList<Week> ,每个ArrayList<Week>包含一个星期ArrayList<Week>的列表ArrayList<Day> ,每个ArrayList<Day>都包含Day类中的Date对象。 In other words, Weeks, have Days, have Dates. 换句话说,周,天,日期。

For a problem I have to randomize the ArrayList<Week> , which I use Collections.shuffle for and works fine. 对于问题,我必须将ArrayList<Week>随机化,将其用于Collections.shuffle并可以正常工作。

I then need to put them back in order, and I attempted this with: 然后,我需要将它们放回原处,并且尝试使用以下方法:

public void sortWeeksInDateOrder(final List<Week> weeks) {
Collections.sort(weeks, new Comparator<Week>() {
        @Override
        public int compare(final Week week1, final Week week2) {
        //Return -1 or 1 if first date is before or after second date.
            return week1.getAllDays().get(0).getDate().before((week2.getAllDays().get(0).getDate())) ? -1 : 1;
        }
    });
}

However it's not sorting. 但是,它没有排序。 Am I missing something? 我想念什么吗? The weeks are never the same so I don't need to return a 0, so I thought this solution would work. 周从不一样,所以我不需要返回0,所以我认为这种解决方案会起作用。

To make it clean, you should implement Comparable interface to Week class and provide implementation details to compareTo method saying how you want to compare Weeks. 为了使其整洁,您应该实现Week类的Comparable接口,并提供实现细节以compareTo方法,以说明如何比较Weeks。

Therefore, it would be enough to write: 因此,编写以下内容就足够了:

Collections.sort(weeks, new Comparator<Week>() {
        @Override
        public int compare(final Week week1, final Week week2) {
            return week1.compareTo(week2);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM