更新时间:2022-05-22 23:46:29
Week week = Week.SUNDAY;
int i = week.ordinal();
请注意,如果更改声明中的枚举常量的顺序,则此值将更改。解决这个问题的一个方法是自动为所有的枚举常量赋值一个int值:
Be careful though, that this value will change if you alter the order of enum constants in the declaration. One way of getting around this is to self-assign an int value to all your enum constants like this:
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);
}
}