Reputation: 1254
I have 2 separate objects, created separately, but when i change one the other once changes too.
Here is the object creation code:
private sMap unsolvedSudoku = new sMap();
private sMap solvedSudoku = new sMap();
private sMap userSudoku = new sMap();
algorithm alg = new algorithm(unsolvedSudoku);
And here is the code that changes one object:
//Generate a new sudoku
alg.generateFullList(); // - This changes unsolvedSudoku
solvedSudoku.setMatrix(unsolvedSudoku.getMatrix()); // - This basically copies an array of numbers from unsolvedSudoku to solvedSudoku.
new algorithm(solvedSudoku).printMap(); // This just prints out the array of numbers
alg.removeRandomNumbers(level); // This removes random numbers from unsolvedSudoku
new algorithm(solvedSudoku).printMap(); // this prints out the array again.
the first printMap and the second printMap are different, but they shouldn't be (at least to my knowledge). Why is that? Also, the sMap class doesn't have any static variables or methods
Upvotes: 0
Views: 123
Reputation: 55233
I suspect the issue is here:
solvedSudoku.setMatrix(unsolvedSudoku.getMatrix());
You're just copying a reference to the same array instance, not actually copying its contents. To copy an array, you can use System.arraycopy()
. The Arrays
utility class also has some useful methods for copying arrays.
I'm assuming from the name "matrix" that this is a 2d array - in that case it will not be as simple as just copying the outer dimension, because the elements will still be references to the same inner arrays. You will need to individually copy each inner array into a new outer array.
I'll leave it up to you to figure this out, since you now have the tools for it.
Upvotes: 5