rocksNwaves
rocksNwaves

Reputation: 6154

Java: copy a single array from a 2d array

While I was browsing answers here, I read that

"Java does not have true 2-dimensional arrays; it has arrays of arrays, so x[rows][cols] is an array x of rows arrays of cols elements (i.e. x[rows] is an array of arrays)."

That seems like good news for me, as I want to create a single 1D array by copying a "row" from a 2D array. What is the correct syntax to call a specific array from P, my 2D array? Essentially:

new double[] row1 = P[row];

Or do I have to loop through the row I want to copy? I have tried the above code and several similar approaches. All receive an error of "Array dimension missing".

Upvotes: 0

Views: 2521

Answers (3)

Michał Szewczyk
Michał Szewczyk

Reputation: 8168

In your code, you are copying reference, instead of an array:

new double[] row1 = P[row];

In case of modification any of them, both would show the result.

To copy the array you can use static method copyOf from Arrays class:

double[][] source = new double[rows][cols];
double[] destination = Arrays.copyOf(source[rowNumber], source[rowNumber].length);

The other way of doing this is by using static method arraycopy from System class:

System.arraycopy( source[rowNumber], 0, destination, 0, source[rowNumber].length );

And the lastone is by invoking clone method:

double[] destination = source[rowNumber].clone();

Upvotes: 1

thatguy
thatguy

Reputation: 22079

If you want a reference to a row, you can use double[] selectedRow = P[rowToSelect]. The new keyword in your code is misplaced. If you want a real copy or better known as deep copy, you can use:

double[] selectedRow = new double[P[rowToSelect].length];
System.arraycopy(P[rowToSelect], 0, selectedRow, 0, P[rowToSelect].length);`

Upvotes: 1

pathfinderelite
pathfinderelite

Reputation: 3137

The easiest way is to use a reference, rather than a copy:

final double[] row1 = P[row];

However, if you need a copy, you can do this:

final double[] row1 = Arrays.copy(P[row], P[row].length);

This of-course assumes P is of type double[][] and row is an int which is within the valid index range.

Upvotes: 1

Related Questions