[英]For loop iterating through table
Say I created a table 说我创建了一张桌子
char[][] table = new char[5][5];
and that I wanted to iterate it using a for loop
for creating a "space." 而且我想使用for loop
来迭代它以创建“空间”。
for (int i = 0; i < table.length; i++)
for (int j = 0; j < table[i].length; j++)
table[i][j] = ' ';
In the second line what does the [i] mean in table[i].length
? 在第二行中,[i]在table[i].length
什么意思? why can't it be just table.length like the first line? 为什么不能像第一行一样只是table.length? Thank 谢谢
Your declaration : 您的声明:
char[][] table = new char[5][5];
is equivalent to : 等效于:
// declare array of size 5, each element is a reference to one-dimen char[] array
char[][] table = new char[5][];
// initialize elements of table array, i.e. each row
table[0] = new char[5];
table[1] = new char[5];
table[2] = new char[5];
table[3] = new char[5];
table[4] = new char[5];
Note: you could have initialized each "row" with arrays of different size, for instance 注意:例如,您可能已经用大小不同的数组初始化了每个“行”
table[3] = new char[255];
and table[1].length
will be 5, while table[3].length
will be 255. 并且table[1].length
将为5,而table[3].length
将为255。
These sizes of ["rows"] arrays are independent of "aggregate" array size table.length
, therefore you have to loop thru each "row" using size of this "row" array. 这些[“ rows”]数组的大小与“ aggregate”数组大小table.length
,因此,您必须使用此“ row”数组的大小遍历每个“ row”。
It is there because you are iterating over two dimensional array. 它在那里是因为您要遍历二维数组。 I recommend you to check out two dimensional array. 我建议您检查一下二维数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.