枚举器与构造函数并在交换机JAVA中使用它

时间:2014-10-04 09:21:37

标签: java android enums switch-statement

我有枚举,例如:

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 (indexSector) {
    case Type.Type2.getValue():
    //...
    break;
}

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

3 个答案:

答案 0 :(得分:2)

Type indexSector = ...;
int value = indexSector.getValue();
switch (indexSector) {
    case Type2:
        // you can use the int from the value variable
        //...
    break;
}

答案 1 :(得分:1)

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

Type x = ...

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

答案 2 :(得分:0)

Type indexType = ...
switch (indexType) {
    case Type.Type1:
    //...
    break;
    case Type.Type2:
        int indexValue = indexType.getValue();
    //...
    break;
    case Type.Type3:
    //...
    break;
    default:
    break;
}