バイナリを使用して各オプションを少し扱い、ユニークなステータスを取得する方法があります。非常に簡単な例は、(この例では、良い実装ではありませんのでご注意これは、可能性のあるアプローチの単なるデモンストレーションである。):
public static void main(String[] args) {
//each booleans represents an option (the state of one check box)
//this example simulates 3 options
boolean option1 = true;
boolean option2 = true;
boolean option3 = true;
//represent each boolean as binary (0 or 1) string
String binString1 = (option1) ? "1" : "0";
String binString2 = (option2) ? "1" : "0";
String binString3 = (option3) ? "1" : "0";
//add all strings to one word
String binaryAsString = binString1+binString2+binString3;
//phrase it to int
// Use as radix 2 because it's binary
int number = Integer.parseInt(binaryAsString, 2);
//for 3 options (bits) you will get 8 different values, from
//0 (all false) to 7 (all true)
System.out.println(option1 + " "+ option2 + " "+ option3 + " = "+ number);
}
出力リレーの例:
偽偽偽= 0
偽偽真= 2
真TRUE TRUE = 7
上記実証思想の可能な実装:
/**
*<pre>
* Converts an array of booleans, in the ordered entered, to a binary word,
* where each boolean represents one bit. The binary word is returned as int.
* <br>usage example:
* <br> boolToInt(false,true,false) returns 2(binary 010).
* <br> boolToInt(true,true,false) returns 6(binary 110).
*
*@param bols
*@throws IllegalArgumentException if bols is null or empty.
*@return
*<pre>
*/
private static int boolToInt(boolean ... bols) {
if((bols == null) || (bols.length == 0)) {
throw new IllegalArgumentException("Invalid (null or empty)input");
}
StringBuilder sb = new StringBuilder();
for(boolean b : bols) {
sb.append((b) ? "1" : "0" );
}
return Integer.parseInt(sb.toString(), 2);
}