Can I use bitwise OR for Java Enums

后端 未结 3 1928
别跟我提以往
别跟我提以往 2021-01-07 21:32

Suppose you have an enum Direction

enum Direction{
    North,South,East West
}

Could I write a method that uses bitwise or\'s to compare mu

相关标签:
3条回答
  • 2021-01-07 22:10

    You can't use a bitwise or like that. Try something more like this:

    public boolean canGoDirection(Set<Direction> dirs){
         return dirs.contains(Direction.North);
    }
    

    called like this:

    this.canGoDirection(EnumSet.of(Direction.South,Direction.North));
    
    0 讨论(0)
  • 2021-01-07 22:17

    The functionality that you are looking for is implemented by EnumSet.

    Your example can be boiled to:

    final static EnumSet<Direction> ALLOWED_DIRECTIONS =
        EnumSet.of( Direction.North, Direction.South );
    
    public boolean canGoDirection(Direction dir){
         return ALLOWED_DIRECTIONS.contains( dir );
    }
    
    0 讨论(0)
  • 2021-01-07 22:24

    Not directly, but if you add a primitive (e.g. int) field to your enum, you can OR that int value.

    However, the resulting value is of int (which can not be implicitly converted to boolean, much less back to enum).

    Probably you would be better off using an EnumSet instead. This is much more idiomatic to Java.

    0 讨论(0)
提交回复
热议问题