Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple flags in one int value

Tags:

java

eclipse

I have a int variable which hold multiple flags, for instance:

int styles = ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED;

I can test the presence of a flag

boolean expanded = (styles & ExpandableComposite.EXPANDED) != 0;

How can I clear the value of a flag from styles, i.e. dynamically remove ExpandableComposite.EXPANDED, without knowing the exact flags which are set in styles?

like image 633
Robert Munteanu Avatar asked Jun 18 '09 08:06

Robert Munteanu


People also ask

What is flag Enum?

Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

Why should we use flag in C?

Flag is used as a signal in a program. Its use is not limited to just C programming, it can be used in just about any code, language independent. Its purpose is to control the program's execution and is also used to debug the program in some cases.

What does the flag specify in C?

A "flag" variable is simply a boolean variable whose contents is "true" or "false". You can use either the bool type with true or false , or an integer variable with zero for "false" and non-zero for "true".


1 Answers

this is an old C idiom, still working in Java:

styles &= ~ExpandableComposite.EXPANDED;

However these days (>= Java 1.5) you should consider using:

  • Enum (see Tutorial)
  • EnumSet
  • EnumMap
like image 114
dfa Avatar answered Oct 24 '22 07:10

dfa