我想将枚举变量声明为值.我怎样才能做到这一点?
例如:
public enum CardSuit { SPADE(0),HEART(1),DIAMOND(2),CLUB(3); }
我可以这样声明:
CardSuit s = CardSuit.SPADE;
我也想这样声明:
CardSuit s = 1;
这样做的方法是什么?这甚至可能吗?
解决方法
我想你想要这样的东西,
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); }
输出是
SPADE
编辑
如果你想按指定的值搜索,你可以用这样的东西来做 –
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); }
输出是
CLUB