数每个枚举项目? [英] Number for each enum item?

查看:122
本文介绍了数每个枚举项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Java中定义这样的事?

Is it possible to define something like this in java?

C#code:

public enum Character
{
    A = 1,

    B = 2,

    C = 4,

    D = 8

}


...

Character ch = /* from user */

if(ch & Character.A)
{
    // some operation...
}

例如,如果 CH 设置为 Character.B 那么结果,如果

for example if ch set to Character.B then result of if will be false:

ch = 00000000 00000000 00000000 00000010
A  = 00000000 00000000 00000000 00000001
------------------------------------------
&    00000000 00000000 00000000 00000000

我要实现这样的事情!有没有可能在Java中?

I want to implement something like that! Is it ever possible in Java?

推荐答案

好了,你可以的的做到这一点:

Well, you can nearly do that:

public enum CharEnum // Let's avoid java.lang.* clashes
{
    A(1), B(2), C(4), D(8);

    private final int mask;

    private CharEnum(int mask)
    {
        this.mask = mask;
    }

    public int getMask()
    {
        return mask;
    }
}

然后:

CharEnum ch = /* from user */

if ((ch.getMask() & CharEnum.A.getMask()) > 0)
{
    // some operation...
}

这可能是在某些情况下是有用的,但正如迈克尔说你一定要看看的 EnumSet 一般设置值选项。

This can be useful in some situations, but as Michael said you should definitely look at EnumSet for general "set of values" options.

如果您的的决定去与值的枚举,你可以把枚举本身额外的逻辑:

If you do decide to go for an enum with values, you can put extra logic within the enum itself:

public enum CharEnum
{
    // Other code as before

    public boolean overlapsWith(CharEnum ch)
    {
        return (ch.mask & mask) > 0;
    }
}

这篇关于数每个枚举项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆