【问题标题】:associating int value to enum and getting corresponding int value将 int 值关联到 enum 并获取相应的 int 值
【发布时间】:2015-09-22 14:16:16
【问题描述】:

我有一个枚举,并且我有一个与每个相关联的整数值。我的一个函数接受该枚举。在函数体中,我想获取关联的 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 值作为键和枚举作为值来创建映射。所以这不能用于在不遍历地图的情况下使用枚举获取数值

How to get enum's numeric value?

【问题讨论】:

  • 你试过在你的枚举上调用 .ordinal() 吗?
  • @Paddyd 他的 int 参数与序数不匹配。
  • @EpicPandaForce 是的,我刚刚注意到:/
  • 为什么不:public static int getCode(TAXSLAB tSlab) { return tSlab.code; }?既然调用者手头有一个枚举并且可以调用getCode() 方法,那么该方法的意义何在?
  • EnumSet.allOf(TAXSLAB.class) 可以替换为TAXSLAB.values()

标签: java enums


【解决方案1】:

您不需要映射从enum 对象中检索code,因为调用TAXSLAB.getCode(s) 会产生与s.getCode() 相同的值:

TAXSLAB s = ...
int c1 = TAXSLAB.getCode(s);
int c2 = s.getCode();
// c1 == c2 here

int codeenum TAXSLAB对象的字段,可以直接获取。

这适用于与enum 中的enum 关联的值。如果您需要将值与enum 之外的enum 相关联,最高效的方法是使用专门为此目的设计的EnumMap 类。

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2011-07-13
    • 2013-03-29
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多