4

I want to map integers to enums in Java. The integer needs to be the key and the enum is the value. All examples I've seen has the enum as the value and the integer as the key. I have:

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
    }
}

How can I call getCardStatus() and get back a CardStatus enum? E.g. getCardStatus(2) would return ACTIVE

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Mark
  • 4,428
  • 14
  • 60
  • 116
  • 8
    `return CardStatus.values()[cardStatus];` – Ole V.V. Mar 11 '19 at 16:15
  • I made before one example that can help you: https://stackoverflow.com/questions/54986379/call-parametrised-constructor-in-enum-singleton/54986549#54986549 – Level_Up Mar 11 '19 at 16:18
  • use **ordinal** values – jarvo69 Mar 11 '19 at 16:24
  • 2
    I understand it works, but I don't agree with the solution of using the `values()`. It's too brittle in my opinion since it relies on the order of the values. What if a new value is needed, such as CANCELED with an associated key of -1? – Andrew S Mar 11 '19 at 16:37
  • 1
    @AndrewS Agreed, but using this for now – Mark Mar 12 '19 at 16:26

1 Answers1

4

You can make getCardStatus() static :

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];
    }
}

And use it :

System.out.println(CardStatus.getCardStatus(0));
Nicholas K
  • 15,148
  • 7
  • 31
  • 57