Fastest way to check if an array of boolean contains true

后端 未结 7 913
余生分开走
余生分开走 2021-01-12 04:08

I have an array of boolean entries:

boolean[] myBooleanArray = new boolean[24];

Currently i check if it contains

7条回答
  •  臣服心动
    2021-01-12 04:33

    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/Lists.

    For an array of 24 elements, I wouldn't worry about this anyway. If you had millions of items and expected very few trues (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 trues, need to find out if there are any trues" then your concern for the fastest way is more relevant, and a data structure like the one above would be useful.

提交回复
热议问题