简体   繁体   中英

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.

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? 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:

     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:

    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 [] :

     int[][] array1 = new int[100][]; 
  • Now there is actually no need for temp anymore, leaving main as just:

     int[][] array1 = new int[100][]; int num = 0; array1[num] = setValue(); 
  • Since you probably want to fill the entire 2D array:

     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();

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

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