如何获取枚举的数值? [英] How to get enum's numeric value?
本文介绍了如何获取枚举的数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设您有
public enum Week {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
如何获得 int
表示星期天是0,星期三是3等?
How can one get int
representing that Sunday is 0, Wednesday is 3 etc?
推荐答案
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);
}
}
这篇关于如何获取枚举的数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文