Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];       
}
like image 632
Cferrel Avatar asked Dec 12 '22 13:12

Cferrel


1 Answers

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]]
like image 78
MeBigFatGuy Avatar answered Dec 28 '22 10:12

MeBigFatGuy