Question

I want to declare an enum variable as values. How can I achieve that?

For Example:

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

I can declare like this:

CardSuit s = CardSuit.SPADE;

I want to declare like this too:

CardSuit s = 1;

What is the way of doing that? Is that even possible?

Était-ce utile?

La solution

I think you want something like this,

public static enum CardSuit {
    SPADE(0), HEART(1), DIAMOND(2), 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 wanted to search by the assigned value, you could do it with something like this -

public static enum CardSuit {
    SPADE(0), HEART(1), 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

Autres conseils

You can provide a factory method:

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

    private final int value;
    CardSuit(int value) { this.value = value; }

    public static CardSuit of(int value) {
        for (CardSuit cs : values()) {
            if (cs.value == value) return cs;
        }
        throw new IllegalArgumentException("not a valid value: " + value);
    }
}
public static void main(String[] args) {
    CardSuit s = CardSuit.of(0);
    System.out.println(s);
}

You can keep a map with value and corresponding Enum

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

    private CardSuit(int i) {
        value = i;
    }

    public int getValue() {
        return value;
    }

    private int value;

    private static Map<Integer, CardSuit> getByValue = new HashMap<Integer, CardSuit>();

    public static CardSuit findByValue(int value) {
        if (getByValue.isEmpty()) {
            for (CardSuit cardSuit : CardSuit.values()) {
                getByValue.put(cardSuit.getValue(), cardSuit);
            }
        }
        return getByValue.get(value);
    }

}

and you can do

CardSuit s = CardSuit.findByValue(1);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top