Java 重置和复制二维数组

标签 java arrays

我在 java 中重置二维数组时遇到问题。我有一门接受二维数组的类(class)。我想做的是复制现有数组,编辑该副本,在类的实例中使用该副本,然后将该数组重置为原始数组的副本,所有这些都无需修改原始数组。如果需要更多信息,请询问。提前致谢!

public Iterable<Board> neighbors(){

    Stack<Board> neighbors = new Stack<Board>();

    for (int i = 0; i < N; i++){
        for (int j = 0; j < N; j++){
            if (tiles[i][j] == 0){

                int [][] copy = new int[N][N];
                System.arraycopy(tiles, 0, copy, 0, tiles.length);

                if (i != 0){
                    exch(copy, i, j, i - 1, j);
                    neighbors.push(new Board(copy));
                    copy = null;
                    System.arraycopy(tiles, 0, copy, 0, tiles.length);
                }
                if (i <= N - 2){
                    exch(copy, i, j, i + 1, j);
                    neighbors.push(new Board(copy));
                    copy = null;
                    System.arraycopy(tiles, 0, copy, 0, tiles.length);
                }
                if (j != 0){
                    exch(copy, i, j, i, j - 1);
                    neighbors.push(new Board(copy));
                    copy = null;
                    System.arraycopy(tiles, 0, copy, 0, tiles.length);
                }
                if (j <= N - 2){
                    exch(copy, i, j, i, j + 1);
                    neighbors.push(new Board(copy));
                    copy = null;
                    System.arraycopy(tiles, 0, copy, 0, tiles.length);
                }
            }
        }
    }
    return neighbors;

}

我将代码更改为上面所示的代码,但出现此错误

Exception in thread "main" java.lang.NullPointerException
at java.lang.System.arraycopy(Native Method)
at Board.neighbors(Board.java:74)
at Board.main(Board.java:136)

最佳答案

请记住,在 Java 中,多维数组实际上是引用其他数组的数组。 Java 中的数组内部只能有一个维度。

要复制数组的内容,可以使用 System.arraycopy () 方法。请注意,对于多维数组,这只会将顶级数组的引用复制到相同的内部数组,因此事情会稍微复杂一些:

int[][] copy = new int[original.length][]; // new top-level array of same size
for (int i = 0; i < copy.length; i++) {
    copy[i] = new int[original[i].length]; // new inner array of same size
    System.arraycopy(original[i], 0, copy[i], 0, original[i].length); // copy values
}

关于Java 重置和复制二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549192/

相关文章:

javascript - 在 JavaScript 中使用 json 填充数据库

Javascript - 将匿名函数传递给 Promise.all

java - 为基于 JVM 的项目创建助手 "scripts"

java - 使用android相机拍照( Intent )内存不足错误

java - 使用 Spring Cloud Stream 将 RabbitMQ 消费者绑定(bind)到现有队列

python - 从python中的数组中获取所有可能的值

arrays - 如何从 MongoDB 中的所有子数组中删除元素

javascript - Typescript - 从数组数据中创建 Json 对象

java - 从 HTML Java 中提取文本

java - 使用 Java ME 的诺基亚不支持 FocusControl?