在Java中按降序排序数组

时间:2012-11-07 19:30:30

标签: java arrays sorting

我正在玩数组和枚举,我想知道最有效的方法是创建一个Comparator类来按降序排序这些日期。这是我的代码。

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

使用以下语句,我可以按照创建的顺序打印数组。

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

如何创建Comparator类以按降序对这些日期进行排序? 理想情况下,我希望它对数组进行排序,无论它是按顺序还是按随机顺序排列。 在这个阶段,我不关心不存在的日期(例如2月31日),因为我只是练习和自学...只是想要获得概念:) 感谢。

增加:

    public ArrayList<Cal> sortDescending(ArrayList<Cal> calList){
    Comparator<Cal> c = Collections.reverseOrder();
    Collections.sort(calList, c);
    return calList;
}

1 个答案:

答案 0 :(得分: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;
    }
});
相关问题