2


我可以从两个枚举创建一个枚举(在 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;
        }
    }
}

任何的想法???我真的很想使用switch并分离了枚举谢谢!!!

4

3 回答 3

10

不,您可以创建一个Day枚举并显式列出每个值,也为每种类型提供一个构造函数......但我个人会使用:

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>工作日和另一个非工作日。

于 2012-04-20T13:21:13.137 回答
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;
    }
}
于 2012-04-20T13:23:41.293 回答
0

Effective 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);

}
}
于 2012-04-20T13:41:36.317 回答