Urs*_*eli 6 java arrays concatenation
我有一种情况需要连接两个二维数组.
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<Object[]> result = new ArrayList<Object[]>();
for(Object[] entry: a1) {
result.add(entry);
}
for(Object[] entry: a2) {
result.add(entry);
}
Object[][] resultType = {};
return result.toArray(resultType);
}
Run Code Online (Sandbox Code Playgroud)
我已经看过这篇文章中一维数组串联的解决方案但是无法使它适用于我的二维数组.
到目前为止,我提出的解决方案是迭代两个数组并将每个成员添加到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);
Run Code Online (Sandbox Code Playgroud)