How do you append two 2D array in java properly?

20,123

Solution 1

Here you go:

import java.util.Arrays;


public class Array2DAppend {

    public static void main(String[] args) {

        int[][] a = new int[][] {{1, 2}, {3, 4}};
        int[][] b = new int[][] {{1, 2, 3}, {3, 4, 5}};

        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(b));
        System.out.println(Arrays.deepToString(append(a, b)));

    }

    public static int[][] append(int[][] a, int[][] b) {
        int[][] result = new int[a.length + b.length][];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }
}

and the output:

[[1, 2], [3, 4]]
[[1, 2, 3], [3, 4, 5]]
[[1, 2], [3, 4], [1, 2, 3], [3, 4, 5]]

Solution 2

If I've understood your problem correctly, this method will append two 2d arrays together -

private static int[][] appendArrays(int[][] array1, int[][] array2) {
    int[][] ret = new int[array1.length + array2.length][];
    int i = 0;
    for (;i<array1.length;i++) {
        ret[i] = array1[i];
    }
    for (int j = 0;j<array2.length;j++) {
        ret[i++] = array2[j];
    }
    return ret;
}

This quick bit of code will test it -

        int[][] array1 = new int[][] {
            {1, 2, 3},
            {3, 4, 5, 6},
    };
    int[][] array2 = new int[][] {
            {11, 12, 13},
            {13, 14, 15, 16},
    };

    int[][] expected = new int[][] {
            {1, 2, 3},
            {3, 4, 5, 6},
            {11, 12, 13},
            {13, 14, 15, 16},
    };


    int[][] appended = appendArrays(array1, array2);
    System.out.println("This");
    for (int i = 0; i < appended.length; i++) {
        for (int j = 0; j < appended[i].length; j++) {
            System.out.print(appended[i][j]+", ");
        }
        System.out.println();
    }
    System.out.println("Should be the same as this");
    for (int i = 0; i < expected.length; i++) {
        for (int j = 0; j < expected[i].length; j++) {
            System.out.print(expected[i][j]+", ");
        }
        System.out.println();
    }

Solution 3

If I understand you correctly, you want to append it, in the opposite dimension, than DomS and MeBigFatGuy thinks. If I'm is correct there are two ways:


If the "column" height (length of 2nd dimension) are fixed within each array you can use this method. It leaves blank (zero-filled) cells, if the arrays have different length of the first dimension. Tho make this code safer, you might want to

/**
 * For fixed "column" height. "Blank cells" will be left, if the two arrays have different "width" 
 */
static int[][] appendArray2dFix(int[][] array1, int[][] array2){
    int a = array1[0].length, b = array2[0].length;

    int[][] result = new int[Math.max(array1.length,array2.length)][a+b];

    //append the rows, where both arrays have information
    int i;
    for (i = 0; i < array1.length && i < array2.length; i++) {
        if(array1[i].length != a || array2[i].length != b){
            throw new IllegalArgumentException("Column height doesn't match at index: " + i);
        }
        System.arraycopy(array1[i], 0, result[i], 0, a);
        System.arraycopy(array2[i], 0, result[i], a, b);
    }

    //Fill out the rest
    //only one of the following loops will actually run.
    for (; i < array1.length; i++) {
        if(array1[i].length != a){
            throw new IllegalArgumentException("Column height doesn't match at index: " + i);
        }
        System.arraycopy(array1[i], 0, result[i], 0, a);
    }

    for (; i < array2.length; i++) {
        if(array2[i].length != b){
            throw new IllegalArgumentException("Column height doesn't match at index: " + i);
        }
        System.arraycopy(array2[i], 0, result[i], a, b);
    }

    return result;
}

If you want to allow the column with to vary within each array, this is possible, with a minor change. This doesn't leave any empty cells.

/**
 * For variable "column" height. No "blank cells"
 */
static int[][] appendArray2dVar(int[][] array1, int[][] array2){

    int[][] result = new int[Math.max(array1.length,array2.length)][];

    //append the rows, where both arrays have information
    int i;
    for (i = 0; i < array1.length && i < array2.length; i++) {
        result[i] = new int[array1[i].length+array2[i].length];
        System.arraycopy(array1[i], 0, result[i], 0, array1[i].length);
        System.arraycopy(array2[i], 0, result[i], array1[i].length, array2[i].length);
    }

    //Fill out the rest
    //only one of the following loops will actually run.
    for (; i < array1.length; i++) {
        result[i] = new int[array1[i].length];
        System.arraycopy(array1[i], 0, result[i], 0, array1[i].length);
    }

    for (; i < array2.length; i++) {
        result[i] = new int[array2[i].length];
        System.arraycopy(array2[i], 0, result[i], 0, array2[i].length);
    }

    return result;
}

Test code modified from DomS

public static void main(String[] args) {

    //Test Var

    int[][] array1 = new int[][] {
            {1, 2, 3},
            {3, 4, 5, 6},
    };
    int[][] array2 = new int[][] {
            {11, 12, 13,14 },
            {13, 14, 15, 16, 17},
    };

    int[][] expected = new int[][] {
            {1, 2, 3, 11, 12, 13, 14},
            {3, 4, 5, 6, 13, 14, 15, 16, 17}
    };


    int[][] appended = appendArray2dVar(array1, array2);
    System.out.println("This");
    for (int i = 0; i < appended.length; i++) {
        for (int j = 0; j < appended[i].length; j++) {
            System.out.print(appended[i][j]+", ");
        }
        System.out.println();
    }
    System.out.println("Should be the same as this");
    for (int i = 0; i < expected.length; i++) {
        for (int j = 0; j < expected[i].length; j++) {
            System.out.print(expected[i][j]+", ");
        }
        System.out.println();
    }


    //Test Fix
    array1 = new int[][] {
            {1, 2, 3, 4},
            {3, 4, 5, 6},
    };
    array2 = new int[][] {
            {11, 12, 13},
            {13, 14, 15},
    };

   expected = new int[][] {
            {1, 2, 3, 4,11, 12, 13},
            {3, 4, 5, 6, 13, 14, 15}
    };


    appended = appendArray2dFix(array1, array2);
    System.out.println("This");
    for (int i = 0; i < appended.length; i++) {
        for (int j = 0; j < appended[i].length; j++) {
            System.out.print(appended[i][j]+", ");
        }
        System.out.println();
    }
    System.out.println("Should be the same as this");
    for (int i = 0; i < expected.length; i++) {
        for (int j = 0; j < expected[i].length; j++) {
            System.out.print(expected[i][j]+", ");
        }
        System.out.println();
    }

}
Share:
20,123

Related videos on Youtube

Cferrel
Author by

Cferrel

I am an independent android developer. I can program currently in C++ and Java. I have a BS in applied mathematics.

Updated on April 12, 2020

Comments

  • Cferrel
    Cferrel about 4 years

    I have been trying to append two 2 D arrays in java. Is it possible to get an example because I have been trying to look it up but cannot find one.

    int [][]appendArray(empty,window)
    {
        int [][]result= new int [empty.length][empty[0].length+window[0].length];       
    }
    
    • Kal
      Kal about 13 years
      What are "empty" and "window" ? Is your method signature int[][] appendArray(int[][] empty, int[][] window) ?
  • MeBigFatGuy
    MeBigFatGuy about 13 years
    completely untrue. Java arrays have no such requirement.
  • Liv
    Liv about 13 years
    It's not about whether Java has such requirements! Logically it just doesn't make any sense to append 2 arrays one with 3 columns and one with 5 columns -- because where will the extra 2 columns go? Can you please solve this mystery for me -- in java or any other language?
  • MeBigFatGuy
    MeBigFatGuy about 13 years
    You are thinking of these arrays in too much of a matrix frame of mind. Think of them as a Lisp list construct. I have two shopping lists: one is for clothes and has shirt, shoes, tie. on it. The other is for food and has ice cream, steak, potatoes, bread. I can easily combine these two lists into one, with (cloths (shirt, shoes, tie), food (ice cream, steak, potatoes, bread)) the fact that the second dimension is not uniform length doesn't matter. See my answer for how to code it.
  • MeBigFatGuy
    MeBigFatGuy about 13 years
    In the end multi-dimensional arrays are just single dimensional arrays, where the elements just happen to be arrays themselves.
  • Cferrel
    Cferrel about 13 years
    My professor has these projects that are next to impossible to do. I am transferring out since the other school has alot more help resources and talked to the other comp sci professor and the projects are not bs like this