在Java中初始化多维数组。

时间:2022-05-27 02:09:33

What is the correct way to declare a multidimensional array and assign values to it?

声明多维数组并为其赋值的正确方法是什么?

This is what I have:

这就是我所拥有的:

int x = 5;
int y = 5;

String[][] myStringArray = new String [x][y];

myStringArray[0][x] = "a string";
myStringArray[0][y] = "another string";

7 个解决方案

#1


58  

Try replacing the appropriate lines with:

试着用以下方法替换合适的句子:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

您的代码不正确,因为子数组的长度为y,并且索引从0开始。因此,设置myStringArray[0][y]或myStringArray[0][x]将会失败,因为索引x和y超出了界限。

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

String[] myStringArray = new String[x][y];是初始化一个矩形多维数组的正确方法。如果您希望它是锯齿的(每个子数组可能有不同的长度),那么您可以使用类似于这个答案的代码。但是请注意,如果您想要一个完美的矩形多维数组,那么您必须手工创建子数组的断言是不正确的。

#2


88  

Java doesn't have "true" multidimensional arrays.

Java没有“真正的”多维数组。

For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

例如,arr[i][j][k]等价于(arr[i])[j]][k]。换句话说,arr只是数组、数组的数组。

So, if you know how arrays work, you know how multidimensional arrays work!

因此,如果您知道数组是如何工作的,您就知道多维数组是如何工作的了!


Declaration:

声明:

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:

或者,与初始化:

int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

Access:

访问:

int x = threeDimArr[1][0][1];

or

int[][] row = threeDimArr[1];

String representation:

字符串表示:

Arrays.deepToString(threeDimArr);

yields

收益率

"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

#3


55  

You can also use the following construct:

您还可以使用以下构造:

String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                             { "X1", "Y1"},
                                             { "X2", "Y2"},
                                             { "X3", "Y3"},
                                             { "X4", "Y4"} };

#4


12  

You can declare multi dimensional arrays like :

您可以声明多维数组,例如:

// 4 x 5 String arrays, all Strings are null
// [0] -> [null,null,null,null,null]
// [1] -> [null,null,null,null,null]
// [2] -> [null,null,null,null,null]
// [3] -> [null,null,null,null,null]

String[][] sa1 = new String[4][5];
for(int i = 0; i < sa1.length; i++) {           // sa1.length == 4
    for (int j = 0; j < sa1[i].length; j++) {     //sa1[i].length == 5
        sa1[i][j] = "new String value";
    }
}


// 5 x 0  All String arrays are null
// [null]
// [null]
// [null]
// [null]
// [null]
String[][] sa2 = new String[5][];
for(int i = 0; i < sa2.length; i++) {
    String[] anon = new String[ /* your number here */];
    // or String[] anon = new String[]{"I'm", "a", "new", "array"};
    sa2[i] = anon;
}

// [0] -> ["I'm","in","the", "0th", "array"]
// [1] -> ["I'm", "in", "another"]
String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};

#5


7  

Multidimensional Array in Java

Returning a multidimensional array

Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...

Java不支持多维数组。在Java中,二维数组只是数组的数组,一个三维数组是数组的数组,一个四维数组是数组数组的数组,等等。

We can define a two-dimensional array as:

我们可以定义一个二维数组为:

  1. int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}
  2. int[] num = {1,2}, {1,2}, {1,2}, {1,2}
  3. int[ ][ ] num = new int[4][2]

    []num = new int[4][2]

    num[0][0] = 1;
    num[0][1] = 2;
    num[1][0] = 1;
    num[1][1] = 2;
    num[2][0] = 1;
    num[2][1] = 2;
    num[3][0] = 1;
    num[3][1] = 2;
    

    If you don't allocate, let's say num[2][1], it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0;

    如果你不分配,比方说num[2][1],它没有初始化,然后自动分配0,即自动num[2][1] = 0;

  4. Below, num1.length gives you rows.

    下面,num1。长给你行。

  5. While num1[0].length gives you the number of elements related to num1[0]. Here num1[0] has related arrays num1[0][0] and num[0][1] only.
  6. 虽然num1[0]。长度给出与num1相关的元素的数量[0]。这里num1[0]有相关的数组num1[0][0][0]和num[0][1]。
  7. Here we used a for loop which helps us to calculate num1[i].length. Here i is incremented through a loop.

    这里我们使用for循环,它帮助我们计算num1[i].length。这里我通过一个循环递增。

    class array
    {
        static int[][] add(int[][] num1,int[][] num2)
        {
            int[][] temp = new int[num1.length][num1[0].length];
            for(int i = 0; i<temp.length; i++)
            {
                for(int j = 0; j<temp[i].length; j++)
                {
                    temp[i][j] = num1[i][j]+num2[i][j];
                }
            }
            return temp;
        }
    
        public static void main(String args[])
        {
            /* We can define a two-dimensional array as
                 1.  int[] num[] = {{1,2},{1,2},{1,2},{1,2}}
                 2.  int[][] num = new int[4][2]
                     num[0][0] = 1;
                     num[0][1] = 2;
                     num[1][0] = 1;
                     num[1][1] = 2;
                     num[2][0] = 1;
                     num[2][1] = 2;
                     num[3][0] = 1;
                     num[3][1] = 2;
    
                     If you don't allocate let's say num[2][1] is
                     not initialized, and then it is automatically
                     allocated 0, that is, automatically num[2][1] = 0;
                  3. Below num1.length gives you rows
                  4. While num1[0].length gives you number of elements
                     related to num1[0]. Here num1[0] has related arrays
                     num1[0][0] and num[0][1] only.
                  5. Here we used a 'for' loop which helps us to calculate
                     num1[i].length, and here i is incremented through a loop.
            */
            int num1[][] = {{1,2},{1,2},{1,2},{1,2}};
            int num2[][] = {{1,2},{1,2},{1,2},{1,2}};
    
            int num3[][] = add(num1,num2);
            for(int i = 0; i<num1.length; i++)
            {
                for(int j = 0; j<num1[j].length; j++)
                    System.out.println("num3[" + i + "][" + j + "]=" + num3[i][j]);
            }
        }
    }
    

#6


3  

I'll add that if you want to read the dimensions, you can do this:

我要补充的是,如果你想看尺寸,你可以这样做:

int[][][] a = new int[4][3][2];

System.out.println(a.length);  // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2

You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

您还可以有交错数组,其中不同的行有不同的长度,所以a[0]。长度! =[1]. length。

#7


-3  

You can look at this to start off:

你可以从这个开始:

    int [][][] i = {                //third dimension curly brace
                     {               // second dimension curly brace
                        {            //first dimension curly brace
                           1,1,1    //elements
                        },           
                    {3,3,3},    
                    {2,2,2}     
                      },
                      {
                         {
                          1,1,1
                         },
                         {3,3,3},
                         {2,2,2}
                       }
                    };      

#1


58  

Try replacing the appropriate lines with:

试着用以下方法替换合适的句子:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

您的代码不正确,因为子数组的长度为y,并且索引从0开始。因此,设置myStringArray[0][y]或myStringArray[0][x]将会失败,因为索引x和y超出了界限。

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

String[] myStringArray = new String[x][y];是初始化一个矩形多维数组的正确方法。如果您希望它是锯齿的(每个子数组可能有不同的长度),那么您可以使用类似于这个答案的代码。但是请注意,如果您想要一个完美的矩形多维数组,那么您必须手工创建子数组的断言是不正确的。

#2


88  

Java doesn't have "true" multidimensional arrays.

Java没有“真正的”多维数组。

For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

例如,arr[i][j][k]等价于(arr[i])[j]][k]。换句话说,arr只是数组、数组的数组。

So, if you know how arrays work, you know how multidimensional arrays work!

因此,如果您知道数组是如何工作的,您就知道多维数组是如何工作的了!


Declaration:

声明:

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:

或者,与初始化:

int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

Access:

访问:

int x = threeDimArr[1][0][1];

or

int[][] row = threeDimArr[1];

String representation:

字符串表示:

Arrays.deepToString(threeDimArr);

yields

收益率

"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

#3


55  

You can also use the following construct:

您还可以使用以下构造:

String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                             { "X1", "Y1"},
                                             { "X2", "Y2"},
                                             { "X3", "Y3"},
                                             { "X4", "Y4"} };

#4


12  

You can declare multi dimensional arrays like :

您可以声明多维数组,例如:

// 4 x 5 String arrays, all Strings are null
// [0] -> [null,null,null,null,null]
// [1] -> [null,null,null,null,null]
// [2] -> [null,null,null,null,null]
// [3] -> [null,null,null,null,null]

String[][] sa1 = new String[4][5];
for(int i = 0; i < sa1.length; i++) {           // sa1.length == 4
    for (int j = 0; j < sa1[i].length; j++) {     //sa1[i].length == 5
        sa1[i][j] = "new String value";
    }
}


// 5 x 0  All String arrays are null
// [null]
// [null]
// [null]
// [null]
// [null]
String[][] sa2 = new String[5][];
for(int i = 0; i < sa2.length; i++) {
    String[] anon = new String[ /* your number here */];
    // or String[] anon = new String[]{"I'm", "a", "new", "array"};
    sa2[i] = anon;
}

// [0] -> ["I'm","in","the", "0th", "array"]
// [1] -> ["I'm", "in", "another"]
String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};

#5


7  

Multidimensional Array in Java

Returning a multidimensional array

Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...

Java不支持多维数组。在Java中,二维数组只是数组的数组,一个三维数组是数组的数组,一个四维数组是数组数组的数组,等等。

We can define a two-dimensional array as:

我们可以定义一个二维数组为:

  1. int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}
  2. int[] num = {1,2}, {1,2}, {1,2}, {1,2}
  3. int[ ][ ] num = new int[4][2]

    []num = new int[4][2]

    num[0][0] = 1;
    num[0][1] = 2;
    num[1][0] = 1;
    num[1][1] = 2;
    num[2][0] = 1;
    num[2][1] = 2;
    num[3][0] = 1;
    num[3][1] = 2;
    

    If you don't allocate, let's say num[2][1], it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0;

    如果你不分配,比方说num[2][1],它没有初始化,然后自动分配0,即自动num[2][1] = 0;

  4. Below, num1.length gives you rows.

    下面,num1。长给你行。

  5. While num1[0].length gives you the number of elements related to num1[0]. Here num1[0] has related arrays num1[0][0] and num[0][1] only.
  6. 虽然num1[0]。长度给出与num1相关的元素的数量[0]。这里num1[0]有相关的数组num1[0][0][0]和num[0][1]。
  7. Here we used a for loop which helps us to calculate num1[i].length. Here i is incremented through a loop.

    这里我们使用for循环,它帮助我们计算num1[i].length。这里我通过一个循环递增。

    class array
    {
        static int[][] add(int[][] num1,int[][] num2)
        {
            int[][] temp = new int[num1.length][num1[0].length];
            for(int i = 0; i<temp.length; i++)
            {
                for(int j = 0; j<temp[i].length; j++)
                {
                    temp[i][j] = num1[i][j]+num2[i][j];
                }
            }
            return temp;
        }
    
        public static void main(String args[])
        {
            /* We can define a two-dimensional array as
                 1.  int[] num[] = {{1,2},{1,2},{1,2},{1,2}}
                 2.  int[][] num = new int[4][2]
                     num[0][0] = 1;
                     num[0][1] = 2;
                     num[1][0] = 1;
                     num[1][1] = 2;
                     num[2][0] = 1;
                     num[2][1] = 2;
                     num[3][0] = 1;
                     num[3][1] = 2;
    
                     If you don't allocate let's say num[2][1] is
                     not initialized, and then it is automatically
                     allocated 0, that is, automatically num[2][1] = 0;
                  3. Below num1.length gives you rows
                  4. While num1[0].length gives you number of elements
                     related to num1[0]. Here num1[0] has related arrays
                     num1[0][0] and num[0][1] only.
                  5. Here we used a 'for' loop which helps us to calculate
                     num1[i].length, and here i is incremented through a loop.
            */
            int num1[][] = {{1,2},{1,2},{1,2},{1,2}};
            int num2[][] = {{1,2},{1,2},{1,2},{1,2}};
    
            int num3[][] = add(num1,num2);
            for(int i = 0; i<num1.length; i++)
            {
                for(int j = 0; j<num1[j].length; j++)
                    System.out.println("num3[" + i + "][" + j + "]=" + num3[i][j]);
            }
        }
    }
    

#6


3  

I'll add that if you want to read the dimensions, you can do this:

我要补充的是,如果你想看尺寸,你可以这样做:

int[][][] a = new int[4][3][2];

System.out.println(a.length);  // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2

You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

您还可以有交错数组,其中不同的行有不同的长度,所以a[0]。长度! =[1]. length。

#7


-3  

You can look at this to start off:

你可以从这个开始:

    int [][][] i = {                //third dimension curly brace
                     {               // second dimension curly brace
                        {            //first dimension curly brace
                           1,1,1    //elements
                        },           
                    {3,3,3},    
                    {2,2,2}     
                      },
                      {
                         {
                          1,1,1
                         },
                         {3,3,3},
                         {2,2,2}
                       }
                    };