java - 带有构造函数的枚举并在 switch JAVA 中使用它

标签 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 中使用它枚举:

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

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

最佳答案

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

关于java - 带有构造函数的枚举并在 switch JAVA 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191399/

相关文章:

Java 选择 : Store images in JAR or as Base64 sequence?

android - Android 上的 ProGuard 和 Gson (ClassCastException)

android - Android通过API连接本地mysql数据库

java - 在运行时使用 java.lang.annotation 检索 Spring 中的 bean

java - 如何在java中使用removeall()减去ArrayList?

java - Libgdx - 使一个实体部分免受物理影响

c++ - 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?

swift - OptionSetType 和枚举

c# - 我应该将引用表值存储为枚举吗?

java - 部署的 EAR 中的配置文件修改