Home > Blockchain >  How to merge 2 arrays in java?
How to merge 2 arrays in java?

Time:09-30

I am trying to merge array1 and array2, given that they can be any size (array1 and array 2 are always the same size). I don't know how to account for the columns as I have no idea how big they are.

int[][] array1 = { {1,3},{11,12,13}, {6,3,32} };
int[][] array2 = { {1,4}, {1,2,3}, {21,7,23} };

int[][] bigArray = new int[array1.length][];
for (int i = 0; i < array1.length; i  ) {
    for (int j = 0; j < array1[i].length; j  ) {
        bigArray[i][j] = Math.max(array1[i][j], array2[i][j]);
    }
}

My problem is when I form the "bigArray", what do I put in the empty brackets

Edit: My expected result should be an array that contains the largest value in every given position, i.e in this one it would be {{1,4},{11,12,13},{21,7,32}}

CodePudding user response:

Java only supports jagged arrays: each element in the outer array points to another array somewhere else in memory.

You don't put anything in the second empty brackets. Instead, you initialize a new array of the required size inside the loop and assign it to the slot. This will guarantee that each nested array has exactly the size that is required.

int[][] array1 = { {1,3},{11,12,13}, {6,3,32} };
int[][] array2 = { {1,4}, {1,2,3}, {21,7,23} };

int[][] bigArray = new int[array1.length][];
for (int i = 0; i < array1.length; i  ) {
    bigArray[i] = new int[array1[i].length];
    for (int j = 0; j < array1[i].length; j  ) {
        bigArray[i][j] = Math.max(array1[i][j], array2[i][j]);
    }
}

or:

int[][] array1 = { {1,3},{11,12,13}, {6,3,32} };
int[][] array2 = { {1,4}, {1,2,3}, {21,7,23} };

int[][] bigArray = new int[array1.length][];
for (int i = 0; i < array1.length; i  ) {
    int[] a = new int[array1[i].length];
    for (int j = 0; j < a.length; j  ) {
        a[j] = Math.max(array1[i][j], array2[i][j]);
    }
    bigArray[i] = a;
}
  • Related