【发布时间】: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 同意,但暂时使用这个