Week week = Week.SUNDAY;
int i = week.ordinal();
但要小心,如果你改变声明中的枚举常量的顺序,这个值会改变。解决这个问题的一种方法是自定义一个int值到所有的枚举常量,如下所示:
public enum Week
{
SUNDAY(0),
MONDAY(1)
private static final Map lookup
= new HashMap();
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);
}
}