Java 如何初始化一个所有元素都为 False 的 2D 布尔数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21515540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:05:53  来源:igfitidea点击:

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

java

提问by Ray Bae

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

标题描述了问题。这是代码:

boolean planeArray[][];

回答by Christian

Just with

只是与

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

all values will be falseby default.

false默认情况下,所有值都是.



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.

请注意,通过使用最后一种方式,行可以有不同的列数。

回答by Kick

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

您必须初始化数组,并且将 的默认值boolean设置为所有索引元素,即false.

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

回答by Basim Khajwal

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:

布尔值默认为 false,但是您创建的数组尚未初始化,因此您需要为数组的每个维度嵌套 for 循环,如下面的代码所示:

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;
    }
}

回答by Ali Itani

I believe you want something like the following.

我相信你想要像下面这样的东西。

Assuming its a 2x2 array.

假设它是一个 2x2 数组。

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

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

或者,如果它是一个 3x3 数组,您可以只添加您需要的元素。

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.

所以你基本上可以根据你想要的 2d 的大小向行或列添加更多元素。