在Java中数组排序为降序 [英] Sorting Array in Java to descending order
问题描述
我在玩弄数组和枚举,我想知道什么是最有效途径,以创建一个比较类降序排列这些日期进行排序。我的继承人code。
公共枚举月{JAN(1),FEB(2),MAR(3),APR(4),MAY(5),JUN(6)7月(7) ,
AUG(8),七重峰(9),OCT(10),NOV(11),DEC(12);
最终诠释monthBoundary;
月(int y)对{
monthBoundary = Y;}
} 公共枚举日期{FIRST(1),第二(2),第三(3)如(4)
第五(5)... THIRTYFIRST(31);
最终诠释dateBoundary;
日期(INT Z){
dateBoundary = Z;}
} //构造等在这里 私有静态最终名单< CAL和GT;日历=新的ArrayList< CAL和GT;();
静态的 {
对于(月月:Month.values()){
为(日期日期:Date.values()){
calendar.add(新卡尔(日,月));
}
}
} //创建新的日历日期
公共静态的ArrayList< CAL和GT; newCal(){
返回新的ArrayList< CAL和GT;(日历);
}
使用下面的语句我可以打印的顺序排列的创建。
System.out.print(Card.calendar());
你如何建立一个比较类以降序排列这些日期进行排序?
理想我想它的阵列是否已经在顺序或随机顺序排序。
在这个阶段,我不关心不存在的日期(如2月31日),因为我只是练习和自我学习......只是想的概念:)
谢谢你。
增加:
公开的ArrayList< CAL和GT; sortDescending(ArrayList的< CAL和GT; calList){
比较< CAL和GT; C = Collections.reverseOrder();
Collections.sort(calList,C);
返回calList;
}
Collections.sort(名单,新的比较< CAL和GT;(){
@覆盖
公众诠释比较(校准CAL1,加州CAL2){
INT结果= -cal1.getMonth()的compareTo(cal2.getMonth()));
如果(结果== 0){
导致= -cal1.getDate()的compareTo(cal2.getDate()))。
}
返回结果;
}
});
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;
}
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;
}
});
这篇关于在Java中数组排序为降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!