Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
}
like image 476
Fraser Price Avatar asked Jan 01 '14 15:01

Fraser Price


1 Answers

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);
like image 66
Jack Avatar answered Oct 02 '22 16:10

Jack