Reputation: 33
I am having trouble resetting a two-dimensional array in java. I have a class that takes in a two-dimentional array. What I am trying to do is copy an existing array, edit that copy, use that copy in an instance of the class, and reset that array to a copy of the original array, all without modifying the original array. If any more information is needed just ask. Thanks in advance!
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;
}
I changed my code to that shown above but i got this error
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)
Upvotes: 1
Views: 302
Reputation: 4992
Remember that in Java multidimensional arrays are actually arrays referencing other arrays. Internally an array in Java can only have a single dimension.
To copy the content of an array, you can use the System.arraycopy
() method. Note that for multidimensional arrays this will only copy the top-level array's references to the same inner arrays, so things are a little more complicated:
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
}
Upvotes: 2
Reputation: 7730
int [][] copy = tiles;
This is not how you make a copy of an Array , in the above mentioned code copy
is just another reference to tiles Array
Object .
Use System.arraycopy
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
Here if you even change src
, dest
will remain the same
Upvotes: 0