java中的2D数组并将其用作1D

时间:2016-08-12 14:06:42

标签: java arrays multidimensional-array

我正在阅读Java中的一些基本MCQ问题,但我无法理解这一问题。

let url = NSURL("http://pokeapi.co/api/v1/pokemon/55/")!
Alamofire.request(.GET, url).responseJSON { response in
  let result = response.result
  /* handle result */
}

并且命令行调用是

  

java CommandArgsThree 1 2 3

现在我无法理解的是, 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]); } } } 已被声明为2D数组,那么如何在argCopy被赋值为args的情况下将其用作一对几行?

P.S:我也知道argCopy [0]是一维数组,这就是为什么我问我们如何在这里使用二维数组作为一维?意味着这样做是否合法?

6 个答案:

答案 0 :(得分:3)

2D数组是一个数组数组。所以argCopy [0]是索引0处的数组,它是一维数组。

答案 1 :(得分:2)

argCopy是一个2D数组,也就是数组数组。因此,元素argCopy[0]argCopy[1]将保存默认大小为2的1D数组。由于args是1D数组,因此可以从大小为2的空数组重新分配argCopy [0]到称为args的数组。要访问2D数组中每个1D数组的各个元素,您不仅需要识别数组的索引,还要识别元素的索引。例如,argCopy[0][0]将允许您访问第一个数组的第一个元素。如果argCopy[0].length的概念让你感到困惑,那么它就意味着第一个数组的元素数量。在您的情况下,它最初为2,但是一旦您将argCopy[0]重新分配给args,它就会更改为args的长度。

答案 2 :(得分:1)

嗯,argCopy是2D,argCopy[0]分配给的是1D。

答案 3 :(得分:1)

args被指定为位置0的argCopy的第一个元素。;)

答案 4 :(得分:0)

您可以这样做,因为2d数组是一个数组数组。因此,当您执行类似argCopy [0]的操作时,您基本上会询问第一个数组您拥有多少个数组?

请参阅此Oracle tutorial创建,初始化和访问阵列

答案 5 :(得分: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
    }
}
}

评论