Create multidimensional array with undefined length of variable strings (Java)

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

Basically I am making a method that will add the values โ€‹โ€‹of two multidimensional arrays of integers together to create a third multidimensional array. This is identical to matrix addition in cases where multidimensional arrays are ARE (e.g. two 2x3 arrays are added together), but not so if I have a multidimensional array with variable string length. So far I have a method:

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 with no variable length strings; however, except for the first part, which verifies 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 problem I am running into is that I cannot declare the "sum" MD array without specifying the dimensions ... Is there a way to create the sum array in a for loop? 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!

+3


source to share


1 answer


You can: int[][] sum = new int[a.length][];

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 multidimensional array in Java is really an array of arrays. (Which doesn't have to be, but it is.)

(In general, you should probably throw away IllegalArgumentException

when the two arrays are not the same size, rather than returning zero. Your code will be much easier to use.)

+1


source







All Articles