Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use bitwise OR for Java Enums

Tags:

java

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);
like image 218
amccormack Avatar asked Feb 10 '11 16:02

amccormack


People also ask

Are enums thread safe in Java?

Creation of Enum instance is thread-safe By default, the Enum instance is thread-safe, and you don't need to worry about double-checked locking. In summary, the Singleton pattern is the best way to create Singleton in Java 5 world, given the Serialization and thread-safety guaranteed and with some line of code enum.

Can you use == for enums Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can Java enums have methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Can you loop through enums?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.


2 Answers

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));
like image 110
Dave L. Avatar answered Oct 24 '22 22:10

Dave L.


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 );
}
like image 40
Alexander Pogrebnyak Avatar answered Oct 24 '22 20:10

Alexander Pogrebnyak