简体   繁体   中英

Sorting Array in Java to descending order

I'm playing around with arrays and enums and i was wondering whats the most effect way to create a Comparator class to sort these dates in descending order. Heres my code.

   public enum Month {JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), 
                      AUG(8), SEPT(9), OCT(10), NOV(11), DEC(12);    
       final int monthBoundary;
       Month(int y){
       monthBoundary=y;}
   }

   public enum Date {FIRST(1), SECOND(2), THIRD(3), FORTH(4), 
                     FIFTH(5)... THIRTYFIRST(31);
       final int dateBoundary;
       Date(int z){
       dateBoundary=z;}
   }

   //constructor etc here

   private static final List<Cal> calendar = new ArrayList<Cal>();
   static {
     for (Month month : Month.values()) {
        for (Date date : Date.values()) {
            calendar.add(new Cal(date, month));
        }
     }
  }

  //creates new calendar dates
  public static ArrayList<Cal> newCal() {
    return new ArrayList<Cal>(calendar); 
  }

Using the following statement i can print the array in the order its created.

   System.out.print(Card.calendar());

How do you create a Comparator class to sort these dates in descending order? Ideally i would like it to sort the array whether it was already in order or in a random order. At this stage i am not concerned about dates that do not exist (eg Feb 31st) as i'm merely practising and self studying... Just trying to get the concept :) Thanks.

ADDED:

    public ArrayList<Cal> sortDescending(ArrayList<Cal> calList){
    Comparator<Cal> c = Collections.reverseOrder();
    Collections.sort(calList, c);
    return calList;
}
Collections.sort(list, new Comparator<Cal>() {
    @Override
    public int compare(Cal cal1, Cal cal2) {
        int result = -cal1.getMonth().compareTo(cal2.getMonth()));
        if (result == 0) {
            result = -cal1.getDate().compareTo(cal2.getDate()));
        }
        return result;
    }
});

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