I have a boolean array in java:
boolean[] myArray = new boolean[10];
What\'s the most elegant way to check if all the values are true?
I can't believe there's no BitSet solution.
A BitSet is an abstraction over a set of bits so we don't have to use boolean[] for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long values to store the bits and doesn't therefore check every bit separately like we do with boolean[].
BitSet myBitSet = new BitSet(10);
// fills the bitset with ten true values
myBitSet.set(0, 10);
For your particular case, I'd use cardinality():
if (myBitSet.cardinality() == myBitSet.size()) {
// do something, there are no false bits in the bitset
}
Another alternative is using Guava:
return Booleans.contains(myArray, true);