2017-03-03 57 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; 
} 
相关问题