java - 将 java 枚举映射到整数

标签 java enums integer

<分区>

我想在 Java 中将整数映射到枚举。整数需要是键,枚举是值。我见过的所有示例都以枚举作为值,以整数作为键。我有:

enum CardStatus {
    UNKNOWN, // 0 should map to this
    PENDING, // 1 should map to this
    ACTIVE // 2 should map to this

    public CardStatus getCardStatus(int cardStatus) {
        // e.g. cardStatus of 1 would return PENDING
    }
}

如何调用 getCardStatus() 并取回 CardStatus 枚举?例如。 getCardStatus(2) 将返回 ACTIVE

最佳答案

您可以使 getCardStatus() 静态化:

enum CardStatus {
    UNKNOWN, // 0 should map to this
    PENDING, // 1 should map to this
    ACTIVE; // 2 should map to this

    public static CardStatus getCardStatus(int cardStatus) {
        return CardStatus.values()[cardStatus];
    }
}

并使用它:

System.out.println(CardStatus.getCardStatus(0));

关于java - 将 java 枚举映射到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55106101/

相关文章:

c - 找到最小的 n 个整数

integer - 为什么 MP3 文件使用同步安全整数?

java - 使用 Java ProcessBuilder 执行 "echo"不会插入变量(输出字符串 "$PATH")

string - 随机字母返回空白

java - 在Java中将文件名/目录传递到命令行

java - 为什么构造函数未定义?

java比较两个枚举

仅用一个整数表示一组整数的算法

java - Spring Boot从1.5.x升级到2.1.x期间如何解决 "AutoConfigure cycle detected"

java - 编程技巧: not able to modify variable before constructor call