简体   繁体   中英

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. 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.

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.

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.

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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