Search code examples
javaarraysappendconcatenationcell

Append two 2D arrays without use of the Java arrays class


I'm confused on how to make a java method to append two different 2D arrays without using/importing the arrays class. This is what I have so far:

private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
    Cell[][] third = new Cell[first.length][first[0].length + second[0].length];

    for (int i = 0; i < first.length; i++) {
        for (int j = 0; j < first[i].length; j++) {
            third[i][j] = first[i][j];
        }
    }
    for (int i = 0; i < second.length; i++) {
        for (int j = 0; j < second[i].length; j++) {
            // don't know what to do here
        }
    }
    return third;
}

A Cell is just an object, but I'm trying to understand the logic behind appending arrays so any help would be appreciated!

Also, I know there is a similar question found here (How do you append two 2D array in java properly?), but the answer is given on appending arrays from the top down (given both parameter arrays have the same amount of columns), while I am looking for appending arrays from side to side (assuming both parameter arrays have the same amount of rows).


Solution

  • You're almost there. I think something like this is what you're looking for.

    private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
        Cell[][] third = new Cell[first.length][first[0].length + second[0].length];
    
        for (int i = 0; i < first.length; i++) {
            for (int j = 0; j < first[i].length; j++) {
                third[i][j] = first[i][j];
            }
            for (int j = first[i].length; j < first[i].length + second[i].length; j++) {
                third[i][j] = second[i][j-first[i].length];
            }
        }
        return third;
    }