public static void main(String[] args) {
    // TODO Auto-generated method stub
    sortDates(Arrays.asList(new DAY[]{DAY.MON,DAY.WED,DAY.TUE,DAY.THU,DAY.SUN,DAY.SAT,DAY.FRI}));
}
public static void sortDates(List<DAY> dayList){
    Set<DAY> set = new TreeSet<DAY>(dayList);
    for(DAY day : set)
    {
        System.out.println(day);
    }
}
public enum DAY {
    MON("MONDAY"),TUE("TUESDAY"),WED("WEDNESDAY"),THU("THURSDAY"),FRI("FRIDAY"),SAT("SATURDAY"),SUN("SUNDAY");

    private String m_name;

    DAY(String name) {
        m_name=name;
    }
}


这段代码的输出是:

周二
星期三
周四
FRI
SAT考试
太阳

但我希望输出是这样的
太阳

周二
星期三
周四
FRI
SAT考试

这意味着我想自定义排序功能,以将星期日移到第一个。

我怎样才能做到这一点?提前致谢。

最佳答案

尝试这个。

    import java.util.*;

public class SortDays {


     public static void main(String[] args) {
         // TODO Auto-generated method stub
         sortDates(Arrays.asList(new DAY[]{DAY.MON,DAY.WED,DAY.TUE,DAY.THU,DAY.SUN,DAY.SAT}));
     }
     public static void sortDates(List<DAY> dayList){
         Collections.sort(dayList, new Comparator<DAY>() {
                public int compare(DAY day1, DAY day2) {
                    return day1.getWeight() - day2.getWeight();
                }});
         System.out.println("sortedlist is" + dayList.toString());
     }



}

 enum DAY {
     MON("MONDAY", 2) ,TUE("TUESDAY", 3),WED("WEDNESDAY", 4),THU("THURSDAY", 5),FRI("FRIDAY", 6),SAT("SATURDAY", 7),SUN("SUNDAY", 1);

     private String m_name;
     private int m_weight;

     DAY(String name, int weight) {
         m_name=name;
         m_weight = weight;
     }

     public int getWeight() {
         return this.m_weight;
     }
 }

关于java - 如何在Java中自定义排序集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22229762/

10-10 06:50