How to remove a flag in Java
|=
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.