如何获得枚举的数值?

假设你有

public enum Week {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

}

怎么能int代表星期日是0,星期三是3等?

回答:

Week week = Week.SUNDAY;

int i = week.ordinal();

但是请注意,如果您更改声明中的枚举常量的顺序,则此值将更改。解决此问题的一种方法是将int值自定义为所有枚举常量,如下所示:

public enum Week 

{

SUNDAY(0),

MONDAY(1)

private static final Map<Integer,Week> lookup

= new HashMap<Integer,Week>();

static {

for(Week w : EnumSet.allOf(Week.class))

lookup.put(w.getCode(), w);

}

private int code;

private Week(int code) {

this.code = code;

}

public int getCode() { return code; }

public static Week get(int code) {

return lookup.get(code);

}

}

以上是 如何获得枚举的数值? 的全部内容, 来源链接: utcz.com/qa/420454.html

回到顶部