Map java enum's to integers

Mark :

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 :

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78449&siteId=1