gpt4 book ai didi

java - 如何获取枚举的数值?

转载 作者:IT老高 更新时间:2023-10-28 20:56:40 25 4
gpt4 key购买 nike

假设你有

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

关于java - 如何获取枚举的数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com