Here is the method I use to concatenate a 2D array. He partly uses Sergio Nakanishi's answer, but adds the ability to come together in both directions.
/* * Define directions for array concatenation */ public static final byte ARRAY_CONCAT_HORIZ = 0, ARRAY_CONCAT_VERT = 1; /* * Concatenates 2 2D arrays */ public static Object[][] arrayConcat(Object[][] a, Object[][] b, byte concatDirection) { if(concatDirection == ARRAY_CONCAT_HORIZ && a[0].length == b[0].length) { return Arrays.stream(arrayConcat(a, b)).map(Object[].class::cast) .toArray(Object[][]::new); } else if(concatDirection == ARRAY_CONCAT_VERT && a.length == b.length) { Object[][] arr = new Object[a.length][a[0].length + b[0].length]; for(int i=0; i<a.length; i++) { arr[i] = arrayConcat(a[i], b[i]); } return arr; } else throw new RuntimeException("Attempted to concatenate arrays of incompatible sizes."); } /* * Concatenates 2 1D arrays */ public static Object[] arrayConcat(Object[] a, Object[] b) { Object[] arr = new Object[a.length + b.length]; System.arraycopy(a, 0, arr, 0, a.length); System.arraycopy(b, 0, arr, a.length, b.length); return arr; }
source share