[英]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.