0
我有一个枚举,并且每个值都有一个整数值。我的一个函数接受枚举。在函数体中,我想获取关联的int值。我现在正在做的是在静态块中创建一个映射(枚举为键,整数代码为值),并使用此映射获取与枚举相对应的代码。这是做这件事的正确方法吗?或者有没有更好的方法来实现这一目标?将int值与枚举相关联并获取相应的int值
public enum TAXSLAB {
SLAB_A(1),
SLAB_B(2),
SLAB_C(5);
private static final Map<TAXSLAB, Integer> lookup = new HashMap<TAXSLAB, Integer>();
static {
for(TAXSLAB w : EnumSet.allOf(TAXSLAB.class)) {
lookup.put(w, w.getCode());
}
}
private int code;
private TAXSLAB(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static int getCode(TAXSLAB tSlab) {
return lookup.get(tSlab);
}
}
这里是相关的SO帖子。但是这里的答案是建议创建一个int值作为键值的映射。因此,这不能被用来获取使用枚举数值,而不通过地图迭代
你试过在你的enum上调用.ordinal()吗? – Paddyd
@Paddyd他的int参数与序号不匹配。 – EpicPandaForce
@EpicPandaForce是啊,我只注意到:/ – Paddyd