2012-02-24 56 views
0

我有2个独立的对象,分别创建,但是当我改变另一个时,一旦改变了。2“链接”对象

下面是创建对象代码:

private sMap unsolvedSudoku = new sMap(); 
private sMap solvedSudoku = new sMap(); 
private sMap userSudoku = new sMap(); 

algorithm alg = new algorithm(unsolvedSudoku); 

这里是改变一个对象的代码:

//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. 

第一printMap和第二printMap是不同的,但他们不应该(至少据我所知)。这是为什么?此外,SMAP类没有任何静态变量或方法

+0

非常相似,http://stackoverflow.com/questions/9403790/2d-arraylists-in-java/9403834#comment11883555_9403834 – 2012-02-24 21:31:47

回答

5

我怀疑问题就在这里:

solvedSudoku.setMatrix(unsolvedSudoku.getMatrix()); 

你只是复制到同一阵列实例的引用,实际上不是复制其内容。要复制数组,可以使用System.arraycopy()Arrays实用程序类也有一些用于复制数组的有用方法。

我从名称“矩阵”中假设这是一个2d数组 - 在这种情况下,它不会像复制外部维度那样简单,因为元素仍然会引用相同的内部数组。您将需要单独将每个内部数组复制到新的外部数组中。

由于您现在已经拥有了相应的工具,所以我会让您知道这一点。

+0

谢谢,现在我明白了这个问题,但我仍然无法修复它。据我所知,这样做应该这样做: solveSudoku.setMatrix(Arrays.copyOf(unsolvedSudoku.getMatrix(),unsolvedSudoku.getMatrix()。length)); 但它没有帮助。 – Squeazer 2012-02-24 21:59:50

+0

另外,我不确定它是否相关,但它是一个二维数组。 – Squeazer 2012-02-24 22:01:57

+0

@Squeazer - 看我的更新 – 2012-02-24 22:05:09