2D阵列的深层复制

时间:2017-03-22 17:20:28

标签: java

我无法创建2D数组的深层副本。它在复制方法中的for循环中给出了一个空指针异常错误。此外,在我之前的版本中,它没有正确创建深层副本。我以为我修好了,但现在错误出现了。有什么提示吗?

public class Test {

public static String[][] deepCopyStringMatrix(String[][] input) {

    if (input == null)
        return null;
    String[][] result = new String[input.length][input[0].length];
    for (int r = 0; r < input.length; r++) {
        for(int k = 0; k< input[0].length; k++) {
            result[r][k] = new String (input[r][k]);
        }
    }
    return result;
}

public static void printBoard (String [][] board, int m, int n) {

    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            System.out.print(" /" + board[i][j] + "/ "); 
        }
        System.out.println();
    }
}


public static void main (String args[]) {
    String[][] test = new String[1][1];
    String[][] newTest = deepCopyStringMatrix(test);

    test[0][0] = "One";

    newTest[1][0] = "Two";

    printBoard(test,1,1);
    printBoard(newTest,1,1);


}

}
编辑:在阅读了一些答案之后,我发现了我遇到的问题,谢谢。

1 个答案:

答案 0 :(得分:0)

使用java.util.Arrays.copyOf()。

示例:

  String[][] test = new String[1][1];
  String[][] newTest = Arrays.copyOf(test, test.length);

下一个问题:

  newTest[1][0] = "Two";

您正在尝试写入不存在的单元格。

相关问题