简体   繁体   English

将单个数组返回多维数组

[英]Returning a single array to a multidimensional array

Full disclosure; 全面披露; I needed to know this for an assignment. 我需要知道这一点。 I wanted to return a single array to a multidimensional array from a method. 我想从方法将单个数组返回到多维数组。 I circumvented the issue with the below code by returning it to another 1-dimensional array then using a for loop to transfer values. 我通过将以下代码返回到另一个一维数组,然后使用for循环来传递值,从而避免了以下代码的问题。

public class test 
{
    public static void main ( String args[] )
    {
        int[][] array1 = new int [100][5];
        int[] temp = new int [5];
        int num = 0;

        temp = setValue();

        for (int i = 0; i<=4; i++) // cycle 1
        {
            array1[num][i]= temp[i];
        }

        System.out.format("\n\n");

    }

    public static int[] setValue()
    {
        int[] array3 = new int [5];

        for (int i = 0; i<=4; i++)
        {
            array3[i]= 2;
        }

        return array3;
    }
}

Is there a more conventional way to return array3 to array1 without cycle 1? 是否有更常规的方式将array3返回到不具有循环1的array1? Something along the lines of 遵循以下原则

array1[num][] = setValue();

Comments: 评论:

  • The method returns a new array, so no need to initialize temp , or better yet, initialize it to return value: 该方法返回一个新数组,因此不需要初始化temp ,或者更好的是,将其初始化为返回值:

     int[] temp = setValue(); 
  • Java doesn't have 2D arrays, just arrays of arrays, so the entire inner array can be replaced, instead of copying values: Java没有2D数组,只有数组的数组,因此可以替换整个内部数组,而不用复制值:

    for (int i = 0; i <= 4; i++) // cycle 1
    {
    array1[num] = temp;
    }

  • When you do that, you shouldn't allocate the inner arrays, ie replace [5] with [] : 这样做时,您不应该分配内部数组,即用[5]替换[5] []

     int[][] array1 = new int[100][]; 
  • Now there is actually no need for temp anymore, leaving main as just: 现在实际上不再需要temp ,将main保留为:

     int[][] array1 = new int[100][]; int num = 0; array1[num] = setValue(); 
  • Since you probably want to fill the entire 2D array: 由于您可能想填充整个2D数组:

     int[][] array1 = new int[100][]; for (int num = 0; num < array1.length; num++) { array1[num] = setValue(); } 

As @VinceEmigh hinted above you can simply do array1[num] = setValue(); 正如上面的@VinceEmigh所暗示的,您可以简单地执行array1[num] = setValue(); ;。

see 看到

int arr[][] = new int[5][];

for (int x = 0; x < arr.length; x++) {
    arr[x] = setValue();
}
for (int x = 0; x < arr.length; x++) {
    for (int y = 0; y < arr[x].length; y++) {
        System.out.println(arr[x][y]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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