wesleyNeill wesleyNeill - 1 year ago 86
Java Question

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".

Answer Source

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);`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download