Please see the link below as a detailed person has already written it. Flag management by bit operation Game flag management is efficient and easy with bit operations
I want to talk.
int
//Definition.
//You can write it freely, but if you write it by shift operation, you can see the value to be defined next at a glance..
final static int COM_LOLI = 1 << 0;
final static int COM_MOM = 1 << 1;
final static int COM_SIS = 1 << 2;
/**
* next flag:0x0008
* <p>
*How to write comments that I saw in the Android Framework.
*If you write the value to be defined next like this, it's handsome.
*/
//Create.
int flags = COM_LOLI | COM_SIS;
//Flag.
flags |= COM_MOM;
//Flag down.
flags &= ~COM_SIS;
//Check the flag.
boolean isOn = (flags & COM_LOLI) != 0;
//At least 101010 when outputting logs...Put out in the format of.
Integer.toBinaryString(flags);
/**
*Creating a method for log output is troublesome to maintain..
*/
static String decodeFlags(final int flags) {
StringBuilder builder = new StringBuilder();
if ((flags & COM_LOLI) != 0) {
builder.append("LOLI").append(" ");
}
if ((flags & COM_MOM) != 0) {
builder.append("MOM").append(" ");
}
if ((flags & COM_SIS) != 0) {
builder.append("SIS").append(" ");
}
return builder.toString();
}
BitSet
//There is also a BitSet.
BitSet bitSet = new BitSet();
//Flag.
bitSet.set(2);
//Flag down.
bitSet.clear(1);
//Check the flag.
boolean isOn = bitSet.get(3);
//But this is a class used when performing bit operations in earnest
//It's a little tricky to use as a flag.
//I was happy if there was toInteger or toLong
//Maybe it's because we can't guarantee the variable length bit array that is the purpose of the class..
EnumSet
/**
*First define the enum.
*/
enum Complex {
LOLI("Woooooooooooo"),
MOM("Mama!"),
SIS("There are 12 people!");
public final String cry;
Complex(final String cry) {
this.cry = cry;
}
}
//Create.
EnumSet<Complex> flags = EnumSet.of(Complex.LOLI, Complex.SIS);
//Flag.
flags.add(Complex.MOM);
//Flag down.
flags.remove(Complex.SIS);
//Check the flag.
boolean isOn = flags.contains(Complex.SIS);
//Looping on the whole element
for (Complex complex : Complex.values()) {
Log.d("allCry", complex.cry);
}
//Convenient to loop or rotate with only the current element
for (Complex complex : flags) {
Log.d("limitedCry", complex.cry);
}
//Information on "what to do if the flag is set"
//Very convenient because it can be taken out immediately
Use EnumSet unless you have a reason to put it in and out of the DB as it is with speed, memory saving, or int. Regarding the speed, EnumSet was also written in Effective Java that it was fast enough.
Also, the guy who defined the constants of the int flag that represents the same state in * various classes * * in different base notation *, ** sir !! **
Recommended Posts