如何在Java中连接二维数组

我有一种情况需要连接两个二维数组。

Object[][] getMergedResults() { Object[][] a1 = getDataFromSource1(); Object[][] a2 = getDataFromSource2(); // I can guarantee that the second dimension of a1 and a2 are the same // as I have some control over the two getDataFromSourceX() methods // concat the two arrays List result = new ArrayList(); for(Object[] entry: a1) { result.add(entry); } for(Object[] entry: a2) { result.add(entry); } Object[][] resultType = {}; return result.toArray(resultType); } 

我已经看过这篇文章中一维数组连接的解决方案但是无法使它适用于我的二维数组。

到目前为止,我提出的解决方案是迭代两个数组并将每个成员添加到ArrayList,然后返回该数组列表的Array()。 我相信必须有一个更简单的解决方案,但到目前为止还没有一个解决方案。

你可以试试

 Object[][] result = new Object[a1.length + a2.length][]; System.arraycopy(a1, 0, result, 0, a1.length); System.arraycopy(a2, 0, result, a1.length, a2.length); 

您可以使用Apache Commons Library – ArrayUtils 。 仅更改第二维的索引并合并整行。

这是我用于2D数组连接的方法。 它部分使用了Sergio Nakanishi的答案,但增加了两个方向连接的能力。

 /* * 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