简体   繁体   中英

how to copy a multidimensional array to a single array?

i want to copy a multidimensional array of rows and columns that contains random numbers into another local array, but only the rows should be copied, this is what i did:

 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); is wrong. arr[i] is an array, copy[I] is not. I have no idea what r is, but somehow I doubt that it's the number of elements to copy. Check out the documentation at http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#arraycopy-java.lang.Object-int-java.lang.Object-int-int- for what the parameters should be. You need the source and destination arrays to have the same base type and to both be arrays, and the destination array's length to be enough to hold the number of elements copied, which likely is not the number of rows in arr[][] as you assigned it.

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

Here is the correct way to use the arraycopy:

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

A shorter way of writing the above:

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

A third way:

return arr[r].clone();

All three ways will have the same result. As for speed, the first two ways may be a tiny bit faster than the third way.

I think you want something like this

/**
 * 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM