我在 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/