如何连接在Java中二维阵列 [英] How to concatenate two-dimensional arrays in Java

查看:161
本文介绍了如何连接在Java中二维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a situation where I need to concatenate two two-dimensional arrays.

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

我已经看过的一维数组的拼接解决方案这个帖子但一直未能使它成为我的二维数组。

I have looked at the solutions for the concatenation of 1-dimensional arrays in this post but have been unable to make it work for my two-dimensional arrays.

到目前为止,我想出了解决的办法是遍历两个数组过来,每个成员加入到一个ArrayList中,然后该数组列表返回的toArray()。我敢肯定,必须有一个简单的解决方案,但迄今未能提出一个。

So far, the solution I have come up with is to iterate over both arrays and adding each member to a ArrayList and then returning toArray() of that array list. I'm sure there must be an easier solution, but have so far been unable to come with one.

推荐答案

您可以尝试

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中二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆