添加枚举值?

时间:2012-04-20 13:17:33

标签: java enums switch-statement


我可以从两个枚举中创建一个枚举(在switch语句中使用的常量)吗?
有点像...

public class Test{

    public enum WorkDay {Monday, Tuesday, Wednesday, Thursday,Friday};
    public enum WeekEndDay {Sunday, Saturday};

    // it doesn't work ):
    public enum Day{WorkDay.values(),WeekEndDay.values()}; 

    public static void Action(Day d) {

        switch(d){
            case Monday:
                ...;
                break;
            case Tuesday:
                ...;
                break;
            case ...:
                ...;
                break;
            case Saturday:
                ...;
                break;
        }
    }
}

任何想法???我真的想使用开关并将枚举分开 感谢!!!

3 个答案:

答案 0 :(得分:10)

没有。你可以创建一个Day enum和显式列出每个值,为每种类型提供一个构造函数......但我亲自使用:

public enum Day {
    MONDAY(true),
    TUESDAY(true),
    WEDNESDAY(true),
    THURSDAY(true),
    FRIDAY(true),
    SATURDAY(false),
    SUNDAY(false);

    private final boolean workDay;

    private Day(boolean workDay) {
        this.workDay = workDay;
    }

    public boolean isWorkDay() {
        return workDay;
    }
}

然后你可以 在工作日发布EnumSet<Day>,在非工作日发布另一个

答案 1 :(得分:0)

由于WorkDay,WeekEndDay和Day都是不同的类,因此无法组合枚举。 你能做的最好的是:

public enum Day {
    Monday(false),
    Tuesday(false),
    Wednesday(false),
    Thursday(false),
    Friday(false),
    Saturday(true),
    Sunday(true);
    private boolean isWeekendDay;
    private Day(boolean isWeekendDay) {
        this.isWeekendDay = isWeekendDay;
    }
    public boolean isWeekendDay() {
        return isWeekendDay;
    }
}

答案 2 :(得分:0)

有效的Java有一个非常好的枚举示例,可以满足您的要求。作者向您推荐了策略模式。代码可以是:

// The strategy enum pattern
enum SomeActionDay {
    MONDAY(DayActionType.WEEKDAY), TUESDAY(DayActionType.WEEKDAY),
    WEDNESDAY(DayActionType.WEEKDAY), THURSDAY(DayActionType.WEEKDAY),
    FRIDAY(DayActionType.WEEKDAY),
    SATURDAY(DayActionType.WEEKEND), SUNDAY(DayActionType.WEEKEND);
private final DayActionType dayType;
SomeActionDay(DayActionType dayType) { this.dayType = dayType; }
return-type takeAction(parameters) {
    return dayType.takeAction(parameters);
}
// The strategy enum type
private enum DayActionType {
WEEKDAY {
return action(parameters) {
//business logic for weekday. return value
}
},
WEEKEND {
return action(parameters) {
//business logic for weekday. return value
}
};

abstract returntype action(parameters);

}
}