2012-11-30 20 views
-1
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]); 
    } 
} 

和命令行调用是更改多维数组的一行的长度?

>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。任何人解释这一点,这是怎么发生的

+1

你在调试器中试过它,看看这是怎么发生的? – djechlin

+0

我使用命令提示符执行此操作 – Ravi

+1

@coders然后在调试器中运行它并查看它在做什么。低调的研究努力。 – djechlin

回答

7

程序的参数存储在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]); 

是相同的功能为:

for (int i = 0; i < a.length; ++i) 
    System.out.print(" " + a[i]); 
// or even 
for (String str: a) 
    System.out.print(" " + str); 

编辑

如前所述有人自删除他的回答(你不应该有,我upvoting它,而你删除它),java多维数组是锯齿形数组,这意味着多维数组不必具有相同的大小,您可以使行1和行2具有2种不同的大小。因此,这意味着声明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 
+0

好的。这是一段非常奇怪的代码。 – jrajav

+0

回答错误的人是谁?你介意解释......吗? – Alex

+0

是的..请!!! – Ravi

0

变量aa被声明为一个字符串数组的数组,而不是简单的多维数组。当您设置aa[0] = a时,您将数组数组的第一个元素设置为作为参数传递的字符串数组。因此,当您遍历aa[0]的项目时,您正在遍历aa[0] = a语句中放置的项目。