【问题标题】:Map java enum's to integers [duplicate]将java枚举映射到整数[重复]
【发布时间】:2019-08-02 00:25:23
【问题描述】:

我想将整数映射到 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

【问题讨论】:

  • return CardStatus.values()[cardStatus];
  • 我之前做了一个可以帮助你的例子:stackoverflow.com/questions/54986379/…
  • 使用序数
  • 我知道它有效,但我不同意使用values() 的解决方案。在我看来它太脆弱了,因为它依赖于值的顺序。如果需要一个新值,例如关联键为 -1 的 CANCELED 怎么办?
  • @AndrewS 同意,但暂时使用这个

标签: java enums integer


【解决方案1】:

你可以将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));

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多