Can I use bitwise OR for Java Enums

2020-03-09 08:37发布

Suppose you have an enum Direction

enum Direction{
    North,South,East West
}

Could I write a method that uses bitwise or's to compare multiple enums

public boolean canGoDirection(Direction dir){
     return dir | Direction.North;
}

where I would call the above method as

this.canGoDirection(Direction.South | Direction.North);

标签: java
3条回答
做自己的国王
2楼-- · 2020-03-09 09:13

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.

查看更多
smile是对你的礼貌
3楼-- · 2020-03-09 09:25

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));
查看更多
别忘想泡老子
4楼-- · 2020-03-09 09:27

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 );
}
查看更多
登录 后发表回答