How to concatenate two-dimensional arrays in Java

10,509

Solution 1

You could try

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

Solution 2

You could use Apache Commons Library - ArrayUtils. Change only the index for second dimension and merge the whole lines.

Share:
10,509
Urs Beeli
Author by

Urs Beeli

I'm a software developer and have mainly been working in C and C++ for almost 20 years before switching to Java which I have used during the last 5+ years. I've taken up JavaScript and web technologies recently and am hoping to get up to speed in this new world.

Updated on June 16, 2022

Comments

  • Urs Beeli
    Urs Beeli almost 2 years

    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.

    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.