微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐