[英]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.