Ray Bae
Ray Bae

Reputation: 99

How to initialize a 2D Boolean Array with all elements False?

The title describes the question. Here's the code:

boolean planeArray[][];

Upvotes: 2

Views: 38183

Answers (5)

Pranavi Chaturvedula
Pranavi Chaturvedula

Reputation: 41

grid = new boolean[n][n];

Simply typing the above line of code would result in the creation of a (n x n) 2-D array with default values set to false.

However, the complexity remains O(n^2) with or without the usage of 2 loops(nested). It would only reduce the number of lines of code, redundant code.

Upvotes: 0

Ali Itani
Ali Itani

Reputation: 1

I believe you want something like the following.

Assuming its a 2x2 array.

boolean[][] planeArray = new boolean[][]{{true, true},
                                         {true, false}
                                         };

Or if its a 3x3 array, you can just add the elements you need.

boolean[][] planeArray = new boolean[][]{{true, true, true},
                                         {true, true, true},
                                         {true, true, true}
                                        };

and so you basically add more elements to rows or cols depending on the size of the 2d you want.

Upvotes: 0

Basim Khajwal
Basim Khajwal

Reputation: 936

A boolean is by default false however the array which you make hasn't been initialized yetso you would need a nested for loops for each dimension of the array as in the following code:

boolean bool[][] = new bool[10][10];

for(int a = 0; a < bool.length; a++){
    for(int b = 0; b < bool[a].length; b++){
        bool[a][b] = false;
    }
}

Upvotes: -2

Kick
Kick

Reputation: 4923

You have to initialize the array and the default value of boolean will be set to all the indexs element which is false.

boolean planeArray[][]  =  new boolean[row_size][column_size];

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34146

Just with

boolean planeArray[][] = new boolean[rows][columns];

all values will be false by default.


You can also initialize with the number of rows:

boolean planeArray[][] = new boolean[rows][];

and then assign each row an 1D-array:

planeArray[0] = new boolean[columns];
...

Note that by using this last way, rows can have different number of columns.

Upvotes: 14

Related Questions