Java 用布尔值填充二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18004990/
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
Fill two-dimensional array with boolean value
提问by Damian
In my class I have these properties:
在我的课堂上,我有这些属性:
boolean rendered[][] = new boolean[][]{};
String tabs[] = { "Tab 1", "Tab 2" };
int rows = 10;
... and I want to create an array with two main levels (two elements in tabs
array), and each level would have 10 (variable rows
) elements with false
value.
...并且我想创建一个具有两个主要级别(tabs
数组中的两个元素)的数组,每个级别将有 10 个(变量rows
)具有false
值的元素。
回答by arynaq
You are free to think of it as [row][column] or [column][row] but the former has a history of usage.
您可以自由地将其视为 [row][column] 或 [column][row],但前者有使用历史。
int rows = 10, int columns = 2
boolean rendered[][] = new boolean[rows][columns];
java.util.Arrays.fill(rendered[0], false);
java.util.Arrays.fill(rendered[1], false);
回答by chrylis -cautiouslyoptimistic-
You probably want Arrays#fill
:
你可能想要Arrays#fill
:
boolean rendered[][] = new boolean[rows][columns]; // you have to specify the size here
for(boolean row[]: rendered)
Arrays.fill(row, false);
(Arrays#fill
can only work on a one-dimensional array, so you'll have to iterate over the rest of the dimensions in a for
loop yourself.)
(Arrays#fill
只能处理一维数组,因此您必须自己在循环中迭代其余维度for
。)
回答by Christopher Francisco
First, you should tell the compiler how long is your array:
首先,你应该告诉编译器你的数组有多长:
boolean rendered[][] = new Boolean[4][5];
Then you can proceed filling it
然后就可以继续填了
for(int i = 0; i < rendered.length; i++)
for(int j = 0; j < rendered[i].length; j++)
rendered[i][j] = false;