有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将多维数组复制到单个数组?

我想将包含随机数的多维行和列数组复制到另一个本地数组中,但只应复制行,这就是我所做的:

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

共 (4) 个答案

  1. # 1 楼答案

    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();
  2. # 2 楼答案

    以下是使用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();
    

    这三种方法都会产生相同的结果。至于速度,前两种方式可能比第三种方式快一点点

  3. # 3 楼答案

    我想你想要这样的东西

    /**
     * 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;
    }
    
  4. # 4 楼答案

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