Java – starts the enumeration as a value

I want to declare enumeration variables as values How can I do this?

For example:

public enum CardSuit {
   SPADE(0),HEART(1),DIAMOND(2),CLUB(3);
}

I can state this:

CardSuit s = CardSuit.SPADE;

I would also like to state:

CardSuit s = 1;

What is the way to do this? Is this even possible?

Solution

I think you want something like this,

public static enum CardSuit {
    SPADE(0),CLUB(3);
    int value;

    CardSuit(int v) {
        this.value = v;
    }

    public String toString() {
        return this.name();
    }
}

public static void main(String[] args) {
    CardSuit s = CardSuit.values()[0];
    System.out.println(s);
}

Output is

SPADE

edit

If you want to search by the specified value, you can do it with something like this –

public static enum CardSuit {
    SPADE(0),DIAMOND(4),CLUB(2);
    int value;

    CardSuit(int v) {
        this.value = v;
    }

    public String toString() {
        return this.name();
    }

    public static CardSuit byValue(int value) {
        for (CardSuit cs : CardSuit.values()) {
            if (cs.value == value) {
                return cs;
            }
        }
        return null;
    }
}

public static void main(String[] args) {
    CardSuit s = CardSuit.byValue(2);
    System.out.println(s);
}

Output is

CLUB
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>