簡體   English   中英

將Java中的數組按降序排序

[英]Sorting Array in Java to descending order

我在玩數組和枚舉,我想知道創建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;
}
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;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM