[英]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. 我在玩数组和枚举,我想知道创建Comparator类以按降序对这些日期排序的最有效方法是什么。 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? 您如何创建Comparator类以按降序对这些日期进行排序? 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. 在这个阶段,我并不担心不存在的日期(例如2月31日),因为我只是在练习和自学……只是想了解这个概念:)谢谢。
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.