2017-03-03 58 views
0

我想複製包含隨機數到另一個本地陣列,但只行應複製的行和列的多維數組,這就是我所做的:如何將多維數組複製到單個數組?

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; 
} 
+1

請添加一些更多的信息,你的問題一樣的期望是什麼,目標平臺/語言等 –

回答

0

這裏是使用arraycopy正確的方法:

return Arrays.copyOf(arr[r], arr[r].length); 

的第三種方式:

int copy[] = new int[arr[r].length]; 
System.arraycopy(arr[r], 0, copy, 0, copy.length); 
return copy; 

寫入上述的一個較短的方式

return arr[r].clone(); 

這三種方式都有相同的結果。至於速度,前兩種方式可能比第三種方式快一點點。

+0

謝謝你,它的工作! – nir

0

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[][]中的行數。

0

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();

0

我想你想是這樣的

/** 
* 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; 
} 
相關問題