Rav*_*avi -1 java arrays multidimensional-array
class B {
public static void main(String a[])
{
int x;
String aa[][]= new String[2][2];
aa[0]=a;
x=aa[0].length;
for(int y=0;y<x;y++)
System.out.print(" "+aa[0][y]);
}
}
Run Code Online (Sandbox Code Playgroud)
并且命令行调用是
>java B 1 2 3
而且选项是
1.)0 0
2.)1 2
3.)0 0 0
4.)1 2 3
我告诉第二个选项是正确的,因为数组是声明的[2][2],所以它不可能是这样的[0][2].但是,回答是1 2 3.任何人解释一下,这是怎么发生的?
程序的参数存储在aa[0]一个数组中,因为它aa是一个数组数组.
所以程序只是迭代了main方法的参数.它打印1, 2, 3(它不关心aa[1]).
int x;
String aa[][]= new String[2][2]; // create an matrix of size 2x2
aa[0]=a; // store the program arguments into the first row of aa
x=aa[0].length; // store the length of aa[0] which is the same as a
for(int y=0;y<x;y++) // iterate over aa[0] which is the same as a
System.out.print(" "+aa[0][y]);
Run Code Online (Sandbox Code Playgroud)
功能与以下相同:
for (int i = 0; i < a.length; ++i)
System.out.print(" " + a[i]);
// or even
for (String str: a)
System.out.print(" " + str);
Run Code Online (Sandbox Code Playgroud)
编辑
如前所述,有人已经删除了他的答案(你不应该,我在删除它的时候正在推销它),java多维数组是锯齿状数组,这意味着多维数组不必是相同尺寸,您可以使第1行和第2行具有2种不同的尺寸.因此,这意味着声明a String[2][2]并不意味着当您重新分配行时,行只需要限制为两列.
String[][] ma = new String[3][2];
ma[0] = new String[] {"a", "b"};
ma[1] = new String[] {"a", "b", "c", "d"}; // valid
String[] foo = new String {"1", "3", "33", "e", "ff", "eee"};
ma[2] = foo; // valid also
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |