[英]how to copy a multidimensional array to a single array?
我想將包含隨機數的行和列的多維數組復制到另一個本地數組中,但是只應復制行,這就是我所做的:
arr = new int[rows][cols];
for(int i = 0; i<arr.length; i++){
for(int j = 0; j<arr[i].length;j++){
arr[i][j] = (int)(range*Math.random());
}
public int[] getRow(int r){
int copy[] = new int[arr.length];
for(int i = 0; i<copy.length;i++) {
System.arraycopy(arr[i], 0, copy[i], 0, r);
}
return copy;
}
System.arraycopy(arr[i], 0, copy[i], 0, r);
是錯的。 arr[i]
是一個數組,而copy[I]
不是。 我不知道r
是什么,但是我不知道這是要復制的元素數量。 在http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#arraycopy-java.lang.Object-int-java.lang.Object-int-int上查看文檔-參數應該是什么。 您需要源數組和目標數組具有相同的基本類型並且都必須是數組,並且目標數組的長度必須足以容納復制的元素數,而arr[][]
的行數可能不等於您分配的。
int[][] stuff = {{1,2,3}, {4,5,6}, {7,8,9}}; for (int[] thing : stuff) println(thing); println(); int[][] myClone = stuff.clone(); // Cloning the outer dimension of the 2D array. for (int[] clone : myClone) println(clone); myClone[0][0] = 100; print('\\n', stuff[0][0]); // Prints out 100. Not a real clone // In order to fix that, we must clone() each of its inner arrays too: for (int i = 0; i != myClone.length; myClone[i] = stuff[i++].clone()); myClone[0][0] = 200; println('\\n', stuff[0][0]); // Still prints out previous 100 and not 200. // It's a full clone now and not reference alias exit();
這是使用arraycopy的正確方法:
int copy[] = new int[arr[r].length];
System.arraycopy(arr[r], 0, copy, 0, copy.length);
return copy;
編寫以上內容的簡短方法:
return Arrays.copyOf(arr[r], arr[r].length);
第三種方式:
return arr[r].clone();
所有這三種方式將具有相同的結果。 至於速度,前兩種方式可能比第三種方式快一點。
我想你想要這樣的東西
/**
* Get a copy of row 'r' from the grid 'arr'.
* Where 'arr' is a member variable of type 'int[][]'.
*
* @param r the index in the 'arr' 2 dimensional array
* @return a copy of the row r
*/
private int[] getRow(int r) {
int[] row = new int[arr[r].length];
System.arraycopy(arr[r], 0, row, 0, row.length);
return row;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.