I have an array
of boolean
entries:
boolean[] myBooleanArray = new boolean[24];
Currently i check if it contains true like so:
Arrays.asList(myBooleanArray).contains(true);
Is this the fastest way to check an array of boolean? If not, what is the fastest way to perform this check?
EDIT:
I timed the methods in your answers as follows by running it as an app on an Android 4.03 Samsung S2 device:
boolean[] myBooleanArray = new boolean[24];
long startTime = System.nanoTime();
suggestedMethod(myBooleanArray);
long endTime = System.nanoTime();
long duration = endTime - startTime;
Log.i("timetest", Long.toString(duration));
Time ranking over five runs were, with fastest first:
Between 5334 and 11584 ns:
for (boolean value : myBooleanArray) {
if (value) {
return true;
}
}
return false;
Between 160542 and 171417 ns:
Arrays.asList(myBooleanArray).contains(true);
Between 191833 and 205750 ns:
Booleans.contains(myBooleanArray, true);
To check if all values in an array are truthy, use the every() method to iterate over the array and return each value straight away. If all values in the array are truthy, the every method will return true , otherwise it returns false .
The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.
In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is . equals() method. By using the Naive approach.
The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false.
Just iterate through array
for(boolean value: myBooleanArray){
if(value){ return true;}
}
return false;
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