Use java.util.BitSet instead. It'd be much faster than dealing with boolean[].
Also, you should really ask yourself if these 20 boolean really should be enum, in which case you can use EnumSet, which is the Java solution to the bit fields technique from C (see: Effective Java 2nd Edition: Use EnumSet instead of bit fields).
BitSet to/from int conversion
You might as well just use BitSet and drop the int, but just in case you need these:
static BitSet toBitSet(int i) {
BitSet bs = new BitSet(Integer.SIZE);
for (int k = 0; k < Integer.SIZE; k++) {
if ((i & (1 << k)) != 0) {
bs.set(k);
}
}
return bs;
}
static int toInt(BitSet bs) {
int i = 0;
for (int pos = -1; (pos = bs.nextSetBit(pos+1)) != -1; ) {
i |= (1 << pos);
}
return i;
}
Two different techniques were deliberately used for instructional purposes. For robustness, the BitSet to int conversion should ensure that 32 bits is enough.
EnumSet example
This example is based on the one given in the book:
import java.util.*;
public enum Style {
BOLD, ITALIC, UNDERLINE, STRIKETHROUGH;
public static void main(String[] args) {
Set<Style> s1 = EnumSet.of(BOLD, UNDERLINE);
System.out.println(s1); // prints "[BOLD, UNDERLINE]"
s1.addAll(EnumSet.of(ITALIC, UNDERLINE));
System.out.println(s1.contains(ITALIC)); // prints "true"
}
}
From the API:
This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."