Are you looking for bitmasking? This is where each bit in an int
represents a boolean value, set (1, means true) and unset (0, means false). For example:
public class MaskingExample {
private static final int OUTSIDE_MASK = 1; // Right-most bit
private static final int HEATED_MASK = 1 << 1; // Second-to-right-most bit
private static final int WET_MASK = 1 << 2; // Third-to-right-most bit
private int value = 0;
public boolean isOutside() {
return isBitSet(OUTSIDE_MASK, value);
}
public void setOutside(boolean outside) {
value = outside ? setBit(OUTSIDE_MASK, value) : unsetBit(OUTSIDE_MASK, value);
}
// Other setters and getters
private static int setBit(int mask, int value) {
return value | mask;
}
private static int unsetBit(int mask, int value) {
return value & ~mask;
}
private static boolean isBitSet(int mask, int value) {
return (value & mask) == mask;
}
}
If you need more than 32 conditions, use long
for all the masks and value
, and add an L
to each of the 1
values being shifted, and you can have up to 64 conditions, like this:
private static final long OUTSIDE_MASK = 1L; // Right-most bit
private static final long HEATED_MASK = 1L << 1; // Second-to-right-most bit
private static final long WET_MASK = 1L << 2; // Third-to-right-most bit
private long value = 0;
You can also set more than one bit at a time too, by the way. You combine masks together into a single mask using &
:
public void setOutsideAndRaining(boolean outsideAndRaining) {
int comboMask = OUTSIDE_MASK & WET_MASK;
value = outsideAndRaining ? setBit(comboMask, value) : unsetBit(comboMask, value);
}
Edit: After seeing kaliatech's answer below, you could also use BitSet
. The solution is very similar, but the math logic is encapsulated in the BitSet
object and it allows for an arbitrary number of bits so you aren't limited to only 64.
public class MaskingExample {
private static final int OUTSIDE_POSITION = 0;
private static final int HEATED_POSITION = 1;
private static final int WET_POSITION = 2;
private static final int TOTAL_CONDITIONS = 3;
private BitSet bitSet = new BitSet(TOTAL_CONDITIONS);
public boolean isOutside() {
return bitSet.get(OUTSIDE_POSITION);
}
public void setOutside(boolean outside) {
bitSet.set(OUTSIDE_POSITION, outside);
}
// Other setters and getters
}