gpt4 book ai didi

java - 如何在Java中连接二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:14:15 25 4
gpt4 key购买 nike

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

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);
}

我已经在 this post 中查看了连接一维数组的解决方案但无法使其适用于我的二维阵列。

到目前为止,我提出的解决方案是遍历两个数组并将每个成员添加到 ArrayList,然后返回该数组列表的 toArray()。我确信一定有更简单的解决方案,但到目前为止还没有找到。

最佳答案

你可以试试

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);

关于java - 如何在Java中连接二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13722538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com