java – 将枚举作为值启动

我想将枚举变量声明为值.我怎样才能做到这一点?

例如:

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

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...