简体   繁体   English

如何将二维数组插入到 Java 中的空 3D 数组中?

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

I'm new to Java, and I'd like to know how I can insert a 2D array (with elements of course) into an empty 3D array using nested for loops 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];
        }
    }
}

In java 2D array is the array of arrays; java中的二维数组是arrays的数组; therefore it's not mandatory for 2D array (row/col) to have each row with the same size.因此,二维数组(行/列)的每一行都具有相同的大小不是强制性的。

The same for 3D array: this is an array of 2D arrays. 3D 阵列也是如此:这是一个二维 arrays 阵列。

So to insert 2D array into 3D array, you just need to set 2D array into 1D array with 2D elements.因此,要将二维数组插入 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

One note, is that in above implementation an array src is now refer to the part of an array dest , so modification of src will be visible in dest .需要注意的是,在上面的实现中,数组src现在指的是数组dest的一部分,因此对src的修改将在dest中可见。 To avoid this effect, you have to create a new copy of src array and insert it into 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