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

Viewed 368

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?

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];
        }
    }
}
1 Answers

In java 2D array is the array of 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.

So to insert 2D array into 3D array, you just need to set 2D array into 1D array with 2D elements.

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. To avoid this effect, you have to create a new copy of src array and insert it into 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);
}
Related