簡體   English   中英

將單個數組返回多維數組

[英]Returning a single array to a multidimensional array

全面披露; 我需要知道這一點。 我想從方法將單個數組返回到多維數組。 我通過將以下代碼返回到另一個一維數組,然后使用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;
    }
}

是否有更常規的方式將array3返回到不具有循環1的array1? 遵循以下原則

array1[num][] = setValue();

評論:

  • 該方法返回一個新數組,因此不需要初始化temp ,或者更好的是,將其初始化為返回值:

     int[] temp = setValue(); 
  • Java沒有2D數組,只有數組的數組,因此可以替換整個內部數組,而不用復制值:

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

  • 這樣做時,您不應該分配內部數組,即用[5]替換[5] []

     int[][] array1 = new int[100][]; 
  • 現在實際上不再需要temp ,將main保留為:

     int[][] array1 = new int[100][]; int num = 0; array1[num] = setValue(); 
  • 由於您可能想填充整個2D數組:

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

正如上面的@VinceEmigh所暗示的,您可以簡單地執行array1[num] = setValue(); ;。

看到

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