Java – How to get a column from a 2D java array

arraysjavamultidimensional-array

I know that 2d arrays are arrays of arrays. To get a row you can do:

rowArray = my2Darray[row]

Since each row can be a different size, I'm assuming it's not built in to get a column from a 2D array. It leads me to believe you'd have to do something like:

for(int row = 0; row < numRows; row++)
{
    colArray[row] = m2Darray[row][columnOfInterest];
}

Is this correct? Is it the only way?

Best Solution

If you are locked down to using a 2d array, then yes, this is it afaik. However, a suggestion that may help you (if possible):

Wrap the array in a class that handles the column fetching.

Good luck.