I have an array
of boolean
entries:
boolean[] myBooleanArray = new boolean[24];
Currently i check if it contains
Generally speaking, if you have an array (or List
) of anything, the fastest/onlyest way to look for an item in it is to iterate over the array until you find what you're looking for. That's one of the limitations of arrays/List
s.
For an array of 24 elements, I wouldn't worry about this anyway. If you had millions of items and expected very few true
s (or possibly none), then it could make sense to encapsulate the data in a class:
public class BooleanArray
{
boolean[] arr = new boolean[SIZE]; // or get size from a constructor
boolean anyTrue = false;
boolean get(int index) {
return arr[index];
}
boolean set(int index, boolean value) {
arr[index] = value;
anyTrue |= value;
}
boolean containsAnyTrues() {
return anyTrue;
}
}
To reiterate, I don't suggest this for your array of 24 elements. I mean it more of an example that your data structure should support the expected use case. If the expected use case is "lots of elements, very sparse true
s, need to find out if there are any true
s" then your concern for the fastest way is more relevant, and a data structure like the one above would be useful.