【发布时间】:2015-11-03 18:26:57
【问题描述】:
我读过这个主题:http://howtodoinjava.com/2012/11/08/a-guide-to-object-cloning-in-java/。
我已经做了一些测试,它可以工作。现在,我的问题是克隆一个对象 A,该对象 A 获得了其他对象 A 的列表。例如:
public class Cell {
Cell[] listOfCells;
}
我在 Cell 类中尝试了以下代码:
public Object clone() throws CloneNotSupportedException {
Cell cloned = (Cell) super.clone();
/* Cloning the list.
* For example, trying to clone the first cell of the list.
*/
Cell[] clonedList = new Cell[listOfCells.length];
clonedList[0] = (Cell) listOfCells[0].clone();
}
问题是,当调用该列表上的方法时,每个单元格都会再次调用该方法,等等,然后,stackoverflow。
编辑:@PaulBoddington 是的,我正在尝试进行深层复制。是的,listOfCells 将包含 this(间接)。简而言之,每个单元格都有一些我用列表表示的邻居(即单元格)。我想要实现的是:克隆一个细胞并通过修改这个克隆,它不会影响原来的。例如:
Cell original;
Cell cloned = original.clone();
cloned.die();
cloned.listOfCells[0].die(); // the first neighbor of the clone
cloned.showState(); // display dead
cloned.listOfCells[0].showState; // display dead
original.showState(); // display alive
original.listOfCells[0].showState(); // the first neighbor of the original, must be alive
【问题讨论】:
-
发布错误堆栈可能会有所帮助;
-
是这个吗?线程“主”java.lang.StackOverflowError 中的异常?
-
如果你尝试做一个深拷贝,如果
listOfCells可以包含this(无论是直接的还是间接的)你会遇到很大的问题。这并非不可能,但我不确定这是否值得。请问您能说明您要达到的目标吗? -
@PaulBoddington 我已经编辑了我的第一篇文章。