2016-08-12 51 views
0

我正在浏览Java中的一些基本的MCQ问题,但我无法理解这一点。Java中的2D数组并将其用作1D

public class CommandArgsThree { 
    public static void main(String[] args) { 
     String[][] argCopy = new String[2][2]; 
     int x; 
     argCopy[0] = args; 
     x = argCopy[0].length; 
     for (int y = 0; y < x; y++) { 
      System.out.print(" " + argCopy[0][y]); 
     } 
    } 
} 

和命令行调用是

的java CommandArgsThree 1 2 3

现在我不能明白的是,argCopy已被宣布为2D阵列然后它如何被用作后面的一对几行,argCopy[0]已被赋值为args的值?

P.S:我也知道argCopy [0]是1D数组,这就是为什么我要问我们如何在2D中使用2D数组作为1D?意味着这样做是合法的吗?

+0

我认为这可能对你会有所帮助: [语法创建一个二维数组(http://stackoverflow.com/questions/12231453/syntax-for-creating-a - 两个维阵列) – SebaJack

回答

2

argCopy是2D阵列又名数组的数组。因此,元素argCopy[0]argCopy[1]将保存默认大小为2的一维数组。由于args是一维数组,因此argCopy [0]可以从大小为2的空数组重新分配到称为args的数组。要访问二维数组中的每个一维数组的单个元素,您不仅必须识别数组的索引,还要识别元素的索引。例如,argCopy[0][0]将允许您访问第一个数组的第一个元素。如果argCopy[0].length的概念让你感到困惑,那么意味着第一个数组的元素数量。在你的情况下,它开始为2,但一旦你重新分配argCopy[0]参数,它改变为args的长度。

0

您可以这样做,因为2d数组是数组的数组。因此,当你做了像argCopy [0]之类的事情时,你基本上问第一个数组,你持有多少个数组?

参见该Oracle tutorial,部分创建,初始化和访问数组

3

2D阵列是数组的数组。所以argCopy [0]是索引为0的数组,它是一维数组。

1

那么,argCopy是2D,但argCopy[0]是分配给1D。

1

ARGS被分配为argCopy的位置0的第一个元素;)

0
public class CommandArgsThree 
{ 
public static void main(String [] args) 
{ 
    String [][] argCopy = new String[2][2]; //Declaration and initialization of argCopy which is a 2D array. 
    int x; //Declaration of an integer x 
    argCopy[0] = args; // In the first index in the 2D array put the 1D String array args 
    x = argCopy[0].length; //Put the length of the array in the 1st index of the 2D array argCopy into x 
    for (int y = 0; y < x; y++) // For loop that runs from 0 till it reaches the value of x 
    { 
     System.out.print(" " + argCopy[0][y]); // Show in the console what is in the array at index y in the 1st index of the 2D array argCopy 
    } 
} 
} 

评论