有没有办法在 Java 中按位或枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6282619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:11:22  来源:igfitidea点击:

Is there a way to bitwise-OR enums in Java?

javaenums

提问by Yet Another Geek

I'm using a state machine, and the code's getting really verbose when testing against a large number of possible states.

我正在使用状态机,并且在针对大量可能的状态进行测试时,代码变得非常冗长。

enum Mood {
    HAPPY, SAD, CALM, SLEEPY, OPTIMISTIC, PENSIVE, ENERGETIC;
}

Is there any way to do this:

有没有办法做到这一点:

if (currentMood == (HAPPY | OPTIMISTIC | ENERGETIC) {}

Instead of this:

取而代之的是:

if (currentMood == HAPPY || currentMood == OPTIMISTIC || currentMood == ENERGETIC) {}

Or would it be better to stick with integers and flags in this case?

或者在这种情况下坚持使用整数和标志会更好吗?

回答by Yet Another Geek

Maybe use something like EnumSet?

也许使用类似EnumSet 的东西?

if (EnumSet<Mood>.of(HAPPY, OPTIMISTIC, ENERGETIC).contains(currentMood))
{ 
 //Do stuff...
}

回答by Mario Marinato

Give your enums an int attribute.

给你的枚举一个 int 属性。

enum Mood {
    private int id;

    HAPPY(1), SAD(2), CALM(4), SLEEPY(8), OPTIMISTIC(16), PENSIVE(32), ENERGETIC(64);

    Mood( int id ) {
        this.id = id;
    }
}

On the if, test against this atrribute.

在 if 上,针对此属性进行测试。

if ( currentMood & ( HAPPY.id | OPTIMISTIC.id | ENERGETIC.id ) != 0 ) { ... }

回答by leonbloy

Apart from other answers: if that particular set of states has a semantically defined meaning in your application (rather independent of your particular method, specific to the Enum) , I'd recommend to included that test as a method in the same Enum class.

除了其他答案:如果该特定状态集在您的应用程序中具有语义定义的含义(而不是独立于您的特定方法,特定于 Enum),我建议将该测试作为方法包含在同一个 Enum 类中。

enum Mood {
     HAPPY, SAD...

     public boolean isRatherPositive() {
       ....
     }

}

(or a static method) to be implemented by any of the logic suggested by the other answers (I'd favour the EnumSet, which could be statically o lazily instantiated).

(或静态方法)由其他答案建议的任何逻辑实现(我更喜欢 EnumSet,它可以静态地 o 懒惰地实例化)。

To have the method in the Enum is useful to avoid code duplication, but above all, to prevent bugs in case you add members to the Enum or modify it.

在 Enum 中使用该方法有助于避免代码重复,但最重要的是,可以防止在向 Enum 添加成员或修改它时出现错误。

回答by Stas Jaro

Yes

是的

switch(currentmood){
    case HAPPY:
    case OPTIMISTIC:...
        Then do this
        break;
    default://else
}

回答by josefx

You could give your enum a boolean flag and test for that.

你可以给你的枚举一个布尔标志并测试它。

enum Mood {
    HAPPY(true), SAD, CALM, SLEEPY, OPTIMISTIC(true), PENSIVE, ENERGETIC(true);
    final boolean good;

    Mood(){this(false);}

    Mood(boolean isgood){this.good = isgood;}

    public isGood(){return good;}
}

This way the check is short

这样支票很短

if (currentMood.isGood()) {}

回答by Dilum Ranatunga

One approach is to have EnumSet/switch/if etc. This makes sense if you are classifying the enumeration in some way that is not intrinsically part of the enumeration itself. For example, whether a color is part of the national flag's color. The 'dependency model' is that national flag depends on Color, but Color doesn't care about the existence of national flags.

一种方法是使用 EnumSet/switch/if 等。如果您以某种方式对枚举进行分类,而这本身并不是枚举本身的一部分,那么这很有意义。例如,颜色是否是国旗颜色的一部分。“依赖模型”是国旗取决于颜色,但颜色并不关心国旗的存在。

On the other hand, if you are trying to determine whether a color is a primary color or not (intrinsic to human model of color), then it belongs on the enum class itself. So,

另一方面,如果您试图确定一种颜色是否是原色(人类颜色模型所固有的),那么它属于枚举类本身。所以,

enum Color {
  private final boolean _crtPrimary;

  Red(true), Green(true), Blue(true), Black(false)

  Color(boolean crtPrimary) {
    _crtPrimary = crtPrimary;
  }

  public boolean isCRTPrimary() {
    return _crtPrimary;
  }
}

回答by Roy Doron

You can use YourEnum.values()

您可以使用 YourEnum。值()

For example, I have Class called Enumerations. In it, I have multiple Enum Classes.

例如,我有一个名为Enumerations 的类。在其中,我有多个 Enum 类。

For example:

例如:

public class Enumerations {

public enum smtg
{
    Fast(1),
    Slow(2);

    private int number;
    private smtg(final int num) { number = num; }
    public int getsmtg()
    {
        return number;
    }
}
......

}

}

When I want to use bitwise, I just use it like that:

当我想按位使用时,我只是这样使用它:

Enumerations.smtg.values()[Enumerations.smtg.Slow.ordinal() | Enumerations.smtg.Fast.ordinal()]

回答by Hunter McMillen

When you use || you have to specify both values you are comparing each time. You could easily write a small method to do this though.

当你使用 || 您必须指定每次比较的两个值。不过,您可以轻松编写一个小方法来执行此操作。

if (currentMood.hasMood(HAPPY, OPTIMISTIC, ENERGETIC)) {}

public boolean hasMood(Mood ....)

回答by ejaenv

Another option:

另外一个选择:

public enum PaymentResponse {
    PP_SUCCESS, PP_FAILURE, CC_SUCCESS, CC_FAILURE;

    public boolean isSuccessful() {
            return ordinal() == CC_SUCCESS.ordinal()  ||  
                   ordinal() == PP_SUCCESS.ordinal() ;
    }
}