Skip to content
Advertisement

Setting all values in a boolean array to true

Is there a method in Java for setting all values in a boolean array to true?

Obviously I could do this with a for loop, but if I have (for example) a large 3D array, I imagine using a loop would be quite inefficient.

Is there any method in Java to set all values in a certain array to true, or alternatively to set all values to true when the array is initialised?

(e.g

boolean[][][] newBool = new boolean[100][100][100];
newBool.setAllTrue();

//Rather than

for(int a = 0; a < 100; a++) {
    for(int b = 0; b < 100; b++) {
        for(int c = 0; c < 100; c++) {
            newBool[a][b][c] = true;
        }
    }
}

Advertisement

Answer

You could use Java 7’s Arrays.fill which assigns a specified value to every element of the specified array…so something like. This is still using a loop but at least is shorter to write.

boolean[] toFill = new boolean[100] {};
Arrays.fill(toFill, true);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement