Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a column from a 2D java array?

Tags:

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?

like image 635
Derrick Avatar asked Jul 10 '09 21:07

Derrick


People also ask

How do you access the rows of a 2D array?

If you want to get the rows, you need to get the values from each array, then create a new array from the values. You can assign the values manually, or use a for-loop, such as this... Otherwise, turn your entire array around so that it stores {row,column} instead of {column,row} , like this...

Are 2D arrays row column?

Arrays in Java can store many items of the same type. You can even store items in two-dimensional (2D) arrays which are arrays that have both rows and columns. A row has horizontal elements. A column has vertical elements.


1 Answers

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.

like image 54
javamonkey79 Avatar answered Sep 24 '22 13:09

javamonkey79