I read a book where the author does this:
public enum Move
{
normal = 0,
swim = 1 << 0,
crawl = 1 << 1,
creep = 1 << 3,
jump = 1 << 3,
fly = 1 << 4,
grapple = 1 << 5,
goes_through_door = 1 << 6
}
Why would you do that, why not just let them have default values like 0,1,2,3...
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. A Java enumeration is a class type.
This is a enum where the values are usable with bitwise operators. It allows for an enum value to be a combination of multiple values. For example
Move crawlAndSwim = Move.crawl | Move.swim;
Bitwise operators can then be used to check for the presence or absence of certain values
if (0 != (aMoveValue & Move.crawl)) {
// It's crawling
}
if (0 != (aMoveValue & Move.swim)) {
// It's swiming
}
Wikipedia has a nice article on this subject which may be of interest to you
Note: As casperOne pointed out, this type of enum definition should be annotated with FlagsAttribute to denote it's a flags / bitfield vs a normal one.
Its so that you can combine them with bit-wise operators. I'm not sure that makes total sense with Move
, but it makes sense with other things.
It has to do with masks.
This way you can represent if it can crawl and swim by a=(crawl | swim)
.
Then you can check the individuals by a&swim
.
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