Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a flag in Java

Tags:

java

flags

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; 
like image 257
Daniel Peñalba Avatar asked Sep 29 '11 10:09

Daniel Peñalba


People also ask

What is flag in Java?

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.


2 Answers

|= 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); 
like image 135
Jon Skeet Avatar answered Oct 03 '22 22:10

Jon Skeet


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.

like image 26
A.H. Avatar answered Oct 03 '22 22:10

A.H.