简体   繁体   中英

2D array in java and using it as 1D

I was going through some basic MCQ questions in Java and I was unable to understand this one.

 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]);
         }
     }
 }

and the command-line invocation is

java CommandArgsThree 1 2 3

Now what I can't understand is that the argCopy has been declared as a 2D array then how can it be used as 1D couple of lines later where argCopy[0] has been assigned the value of args?

PS: I also know that argCopy[0] is 1D array that's why I am asking how can we use the 2D array as 1D here?Means is it legal to do so?

A 2D array is an array of arrays. So argCopy[0] is the array at index 0 which is a 1D array.

argCopy is a 2D array aka an array of arrays. Therefore, the elements argCopy[0] and argCopy[1] will hold 1D arrays of default size 2. And since args is a 1D array, argCopy[0] can be reassigned from an empty array of size 2 to the array known as args . To access the individual elements of each 1D array within the 2D array, you not only have to identify the index of the array but also the index of the element. For example, argCopy[0][0] will let you access the first element of the first array. If the concept of argCopy[0].length confuses you, all it means is the number of elements of the first array. In your case, it started out as 2, but once you reassigned argCopy[0] to args, it changed to the length of args .

好吧, argCopy是2D,但是分配给的argCopy[0]是1D。

args在位置0被分配为argCopy的第一个元素。

You can do this because a 2d array is an array of arrays. Thus when you do something like argCopy[0] you essentially asking the first array how many arrays does you hold?

See this Oracle tutorial , part Creating, Initializing, and Accessing an Array

 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
    }
}
}

Commented

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM