Christian Silva
Christian Silva

Reputation: 37

Creating a multidimensional array with unspecified variable row lengths (Java)

I'm trying to do a few things with multidimensional arrays. I'm new to Java and not an excellent programmer, and I couldn't find anything else on the internet about this topic, so I thought I'd ask here.

Essentially I'm making a method that will add the values of two multidimensional integer arrays together to create a third multidimensional array. This is identical to matrix addition in the cases where the multidimensional arrays ARE matrices (e.g. two 2x3 arrays added together), but not so if I have a multidimensional array with variable row lengths. So far the method I have is this:

public static int[][] addMDArray(int[][] a, int[][] b)
{
    boolean columnequals = true;
    for (int row = 0; row < a.length; row++)
    {
        if (a[row].length != b[row].length)
        {
            columnequals = false;
        }
    }
    if (columnequals == false || a.length != b.length)
        System.out.println("The arrays must have the same dimensions!");
    else
    {
        int[][] sum = new int[a.length][a[0].length];
        for (int row = 0; row < a.length; row++)
        {
            for (int column = 0; column < a[row].length; column++)  
                sum[row][column] = a[row][column] + b[row][column];
        }
        return sum;
    }
    return null;
}

As I said, this works with MD arrays without variable row lengths; however, with the exception of the first part that checks that they have the same dimensions, this method will not work with two arrays like this:

int[][] g = {{2, 1}, {3, 5, 4}, {5, 7, 7}};
int[][] d = {{1, 2}, {3, 4, 5}, {5, 6, 7}};

The issue I'm running into is that I can't declare the "sum" MD array without specifying dimensions... Is there a way to create the sum array in the for loop itself? I feel like this would be the simplest solution (if possible), but otherwise I don't know what else to try.

Any help would be appreciated!

Upvotes: 3

Views: 3865

Answers (1)

biziclop
biziclop

Reputation: 49744

You can: int[][] sum = new int[a.length][]; is perfectly legal. Then you can do sum[i] = new int[a[i].length];, and your code will look like this:

    int[][] sum = new int[a.length][];
    for (int row = 0; row < a.length; row++)
    {
        sum[row] = new int[a[row].length];
        for (int column = 0; column < a[row].length; column++)  
            sum[row][column] = a[row][column] + b[row][column];
    }

Just remember that a multi-dimensional array in Java is really an array of arrays. (Which isn't necessarily how things should be but it is what it is.)

(As a complete aside, you should probably throw an IllegalArgumentException when the two arrays don't have the same dimensions rather than return null. Your code will be a lot easier to use that way.)

Upvotes: 2

Related Questions