Boolean a, b, c, d;
I would like to count the number of trues, each result should have its own associated action. Maybe something like:
int result = getResult(a, b, c, d);
switch (result) {
case 0: break;
case 1: break;
case 2: break;
case 3: break;
default: break;
}
Any idea of how to write the getResult
method body a pretty way? In the example, I used only four, but it should be extendable to a bigger number of booleans. Any other way to proceed is welcome.
Write a variadic method?
int getResult(boolean... vars) {
int count = 0;
for (boolean var : vars) {
count += (var ? 1 : 0);
}
return count;
}
A better solution may be to use a BitSet which can be more efficient esp if you have many boolean values.
BitSet bs = new BitSet();
bs.set(1);
bs.set(4);
bs.set(9);
bs.set(16);
int setCount = bs.cardinality(); // 4
Instead of
boolean a, b, c, d;
you have BitSet which can have hundreds or millions of boolean values.
BitSet bs = new BitSet(4);
bs.set(0); // a
bs.set(1); // b
bs.set(2); // c
bs.set(3); // d
int setCount = bs.cardinality(); // 4
When you have a lot of booleans, this solution scales much better. i.e. each boolean uses one bit, however each Boolean
is a reference and thus uses 32-bits or up to 32x as much memory. Also cardinality()
is implemented for you no matter how many bits/booleans you have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With