I agree with Michael Borgwardt and Jon Skeet that an EnumSet
is worth looking at. I would have picked EnumSet
over bitwise operations like you've got, so I will demonstrate how to use EnumSet
.
It looks like your Character
enum (let's call it CharEnum
from now on) CharEnum
is being used like a bit field, where each enum has an int value with just one bit set:
A = 00000000 00000000 00000000 00000001
B = 00000000 00000000 00000000 00000010
C = 00000000 00000000 00000000 00000100
D = 00000000 00000000 00000000 00001000
This is very similar to what an EnumSet
does for you; it has an internal bit vector that automatically assigns each enum to a bit on a long
. As the JavaDoc for it says, "The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."
Here's an example of how to use it
public enum CharEnum {
A, B, C, D;
}
and then
EnumSet<CharEnum> ch = /* from user */
if (ch.contains(CharEnum.A)) {
// some operation...
}
No need to specify bits anywhere, so it's much simpler code!
A warning: this only works because the enum values in your C# example have only one bit set each. If you had an enum value like this:
E = 00011000 01110111 11100101 10000101
then an EnumSet
would not be appropriate. In that case you should look at one of the other answers here.