簡體   English   中英

如何將二維數組插入到 Java 中的空 3D 數組中?

[英]How to insert a 2D array into an empty 3D array in Java?

我是 Java 的新手,我想知道如何使用 ZD52387880E1EA22817A72D3799 中的嵌套循環將二維數組(當然包含元素)插入到空的 3D 數組中

String[][][] ProductAllData2 = new String[10][getPInputsWithParameter(getPInputs()).length][getPInputsWithParameter(getPInputs()).length];

String [][] receivedPInputsWithParameter = getPInputsWithParameter(getPInputs());
         
for(int i = 0; i < ProductAllData2.length; i++) { //Inserts in 3D array
            
    for(int j = 0; j < ProductAllData2[i].length; j++) {
        ProductAllData2[i][j] = new String[receivedPInputsWithParameter[j].length];
  
        for(int k = 0; k < ProductAllData2[i][j].length; k++) {
            ProductAllData2[i][j][k] = receivedPInputsWithParameter[j][k];
        }
    }
}

java中的二維數組是arrays的數組; 因此,二維數組(行/列)的每一行都具有相同的大小不是強制性的。

3D 陣列也是如此:這是一個二維 arrays 陣列。

因此,要將二維數組插入 3D 數組中,只需將二維數組設置為具有二維元素的一維數組即可。

int[][][] dest = {
        // id = 0
        {
                { 1, 2, 3 },
                { 4, 5, 6 }
        },
        // id = 1
        {
                { 7, 8, 9 },
                { 10, 11, 12 }
        }
};

int[][] src = {
        { 77, 88, 99 },
        { 1010, 1111, 1212 }
};

dest[1] = src;  // replace 2D array with id = 1

需要注意的是,在上面的實現中,數組src現在指的是數組dest的一部分,因此對src的修改將在dest中可見。 為避免這種影響,您必須創建src數組的新副本並將其插入dest

private static void insert(int[][][] dest, int[][] src, int id) {
    int rows = src.length;
    dest[id] = new int[rows][];

    for (int row = 0; row < rows; row++)
        dest[id][row] = Arrays.copyOf(src[row], src[row].length);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM