0

I have this method that adds two 2d boolean arrays together. So for a given cell, if any array is true for that cell, the cell in the resulting array is set to true.

private boolean[][] addBooleanArrays(List<boolean[][]> arrays) {
    boolean[][] result = new boolean[8][8];
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            for (boolean[][] b : arrays) {
                if (b[i][j] == true) {
                    result[i][j] = true;
                }
            }
        }
    }
    return result;
}

I'm feeding this method 16 boolean arrays that I know contain true and false values but I am getting a null pointer exception at the if statement. I can't see why though, maybe I'm missing something. Any help appreciated.

0

3 Answers 3

2

Add a null check to ensure that a particular b isn't null:

if (b != null && b[i][j] == true) {

A for-each loop like you're using will still return each value in arrays, even if the value is null.

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah but my arrays only contain true and false I know that for a fact
Most definitely, since boolean is a primitive type and can't be set to null. But I'm talking about making sure that b, which is a 2-d boolean array, isn't null (see the difference?)
Ok I added that check and a b is null. But I can see how it can be null. My arrays List only has boolean[][]?
That's because arrays (whatever their dimensions; in this case 2-d) are objects, so they can be set to null.
1

A row in the input array is null instead of being a boolean[8].

2 Comments

I thought booleans initialise to false
@Clay You have to realize that there are 9 objects involved. Each array is an object, so a boolean[][] is an object that could be null. Since this is a 2-D array, each element of the array is itself an object, another array, so any of those array elements could also be null. (And if you had said new boolean[8][], the array elements would be initialized to null.) Those last eight arrays are the arrays of boolean, though, and I think those are indeed initialized to false.
0

Maybe some b[i] is null that causes the exception, I suggest you checking the code generating elements of arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.