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);
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.
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.
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.
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.
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));
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With