0

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 (e.g. 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;
}
4
  • Well, what do you think, how it should be done? Have you come up with some code? If yes post it here please. Commented Nov 7, 2012 at 19:33
  • try Collections.sort() with your own comparator Commented Nov 7, 2012 at 19:35
  • @RohitJain I have added the method i tried. I'm not sure if its the best way to implement it Commented Nov 7, 2012 at 20:26
  • @qwertyRocker. It will not work. Because Collections.reverseOrder doesn't know what is the reverseOrder for your Cal. See @JBNizet's answer for what you need. Commented Nov 7, 2012 at 20:28

1 Answer 1

3
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;
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Fixed. Thanks for noticing the mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.