Hi I need to remove a flag in Java. I have the following constants:
public final static int OPTION_A = 0x0001; public final static int OPTION_B = 0x0002; public final static int OPTION_C = 0x0004; public final static int OPTION_D = 0x0008; public final static int OPTION_E = 0x0010; public final static int DEFAULT_OPTIONS = OPTION_A | OPTION_B | OPTION_C | OPTION_D | OPTION_E;
I want to remove, for example OPTION_E from default options. Why is not the following code correct?
// remove option E from defaul options: int result = DEFATUL_OPTIONS; result |= ~OPTION_E;
The Flags class represents the set of flags on a Message. Flags are composed of predefined system flags, and user defined flags. A System flag is represented by the Flags. Flag inner class. A User defined flag is represented as a String.
|=
performs a bitwise or, so you're effectively "adding" all the flags other than OPTION_E
. You want &=
(bitwise and) to say you want to retain all the flags other than OPTION_E
:
result &= ~OPTION_E;
However, a better approach would be to use enums and EnumSet
to start with:
EnumSet<Option> options = EnumSet.of(Option.A, Option.B, Option.C, Option.D, Option.E); options.remove(Option.E);
You must write
result &= ~OPTION_E;
Longer explanation:
You must think in bits:
~OPTION_E // 0x0010 -> 0xFFEF DEFATUL_OPTIONS // -> 0x001F 0xFFEF | 0x001F // -> 0xFFFF 0XFFEF & 0x001F // -> 0x000F
The OR
will never clear 1
bits, it will at most set some more. AND
on the other hand will clear bits.
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