for循环迭代表

时间:2014-04-06 19:08:50

标签: java for-loop

说我创建了一个表

char[][] table = new char[5][5];

我希望使用for loop进行迭代以创建“空格”。

for (int i = 0; i < table.length; i++)
for (int j = 0; j < table[i].length; j++)
       table[i][j] = ' ';   

在第二行中,[i]在table[i].length中的含义是什么?为什么不能像第一行那样只是table.length?感谢

2 个答案:

答案 0 :(得分:2)

您的声明:

char[][] table = new char[5][5];

相当于:

// 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];

注意:您可以使用不同大小的数组初始化每个“行”,例如

table[3] = new char[255];

table[1].length将为5,而table[3].length将为255。

这些[“行”]数组的大小独立于“聚合”数组大小table.length,因此您必须使用此“行”数组的大小循环到每个“行”。

答案 1 :(得分:0)

它就在那里,因为你正在迭代二维数组。我建议你查看二维数组。