Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...