gpt4 book ai didi

java - 如何在Java中自定义Set的排序

转载 作者:行者123 更新时间:2023-12-01 18:35:23 24 4
gpt4 key购买 nike

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

这段代码的输出是:周一治疗费用星期三周四弗瑞SAT太阳

但是我想要的输出是这样的太阳周一治疗费用星期三周四弗瑞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中自定义Set的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com