Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

java - Sort ArrayList of Calendars

I have a list of objects containing hours and minutes. The list is in a chaotic order and I need to sort them by the hour from 00:00 to 23:59.

The object is

public class ProgramItem {
    public int Hours;
    public int Minutes;

    public ProgramItem() {

    }

    public ProgramItem(int hours, int minutes, int power) {
        Hours = hours;
        Minutes = minutes;
    }

    public Calendar getCalendar() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Hours);
        calendar.set(Calendar.MINUTE, Minutes);

        return calendar;
    }
}

The way I sort them is

Collections.sort(items, new Comparator<ProgramItem>() {
        public int compare(ProgramItem item1, ProgramItem item2) {
            if (item1.getCalendar().before(item2.getCalendar())) {
                return -1;
            } else {
                return 1;
            }
        }
})

For example:

The input: 02:00, 09:00, 15:00, 21:00, 00:00, 23:00

The output should be: 00:00, 01:00, 02:00, 09:00, 15:00, 21:00, 23:00

The output I have: 02:00, 09:00, 15:00, 21:00, 23:00, 00:00

The problem is that midnight is always at the end, but I need it to be at the beginning.

How to make sorting starts from 00:00 and ends at 3:00-23:59? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe the the theme is not calendar sorting. If so then do not allocate more memory using Calender object, add this method simply,

public class ProgramItem {
   ....
   int getAsMins() {
      return hours *60 + mins;
   }
}
....
Collections.sort(items, new Comparator<ProgramItem>() {
        public int compare(ProgramItem item1, ProgramItem item2) {
           return item1.getAsMins() - item2.getAsMins();
        }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...