【问题标题】:Enums with constructors and using it in switch JAVA带有构造函数的枚举并在 switch JAVA 中使用它
【发布时间】:2014-10-04 09:21:36
【问题描述】:

我有枚举,例如:

public enum Type {
    Type1(10),
    Type2(25),
    Type3(110);

    private final int value;

    Type(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

我想在 switch 中使用枚举:

switch (indexSector) {
    case Type.Type2.getValue():
    //...
    break;
}

但 IDE 说“需要常量表达式”。如何在 switch 中使用 Enum 这种类型?

【问题讨论】:

    标签: java android enums switch-statement


    【解决方案1】:
    Type indexSector = ...;
    int value = indexSector.getValue();
    switch (indexSector) {
        case Type2:
            // you can use the int from the value variable
            //...
        break;
    }
    

    【讨论】:

    • 谢谢,我明白了。它有效,但没有“Type.Type2:”,只有“Type2:”。
    【解决方案2】:

    您可以在开关中使用枚举,但您的案例必须是枚举本身的项目,而不是方法返回值。

    Type x = ...
    
    switch (x) {
        case Type1: ...
           break;
        case Type2: ...
           break;
        case Type3: ...
           break;
    }
    

    【讨论】:

      【解决方案3】:
      Type indexType = ...
      switch (indexType) {
          case Type.Type1:
          //...
          break;
          case Type.Type2:
              int indexValue = indexType.getValue();
          //...
          break;
          case Type.Type3:
          //...
          break;
          default:
          break;
      }
      

      【讨论】:

      • 你不能在枚举上使用new
      • 不,实际上你不能。在您提供的文章中,他们没有使用 new 关键字创建枚举实例 - 他们创建了一个名为 EnumTest 的包装类的实例。 Ofc,枚举可以有构造函数,但仍然不能使用 new 实例化实例。
      猜你喜欢
      • 1970-01-01
      • 2015-07-09
      • 2011-08-20
      • 1970-01-01
      • 2011-12-27
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多