Johnydep
Johnydep

Reputation: 6277

copying column of a 2D array as 1D array in java?

Let's say I have a 2D array:

int[][] a = new int[4][3];

populated such that:

1 2 3
4 5 6
7 8 9
2 5 7

Is there any shortcut method in java to extract lets say column 1 as single array:

array1 = {1 4 7 2};

Currently what I am doing is traversing through the whole 2D matrix and with if condition (if j==0), I traverse over the rows and add values to 1D array.
Just wondering if there is any standard method offered in java for such tasks.

Upvotes: 3

Views: 4016

Answers (3)

Ed Staub
Ed Staub

Reputation: 15690

You might want to consider use of a matrix library. But this is pretty simple stuff - if this is all you need, you can probably write it quicker than you can get up to speed on a library.

Upvotes: 0

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

No there is no shortcut to doing this. You have to loop over the arrays, switching the x & y indices.

Upvotes: 2

zacheusz
zacheusz

Reputation: 8842

There is no such build-in method. You have to write a simple loop.

Upvotes: 0

Related Questions