我正在做一项任务,简而言之 - 自定义LinkedList。我需要覆盖Object.clone来制作MyLinkedList的深层副本,但我不明白,我是否需要克隆这两个,有问题的和外层的?这是代码:
public class MyLinkedList implements Cloneable {
private Entry header;
private int size;
.....................
@Override
public Object clone() {
MyLinkedList newObject = null;
try {
newObject = (MyLinkedList) super.clone();
newObject.header = this.header.clone();
} catch (CloneNotSupportedException e) {
System.err.print("Clone not supported");
}
return newObject;
}
private static class Entry implements Cloneable {
double data;
Entry prev;
Entry next;
public Entry(double data, Entry next, Entry prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
@Override
public Entry clone() {
Entry newObject = null;
try {
newObject = (Entry) super.clone();
newObject.prev = this.prev.clone();
newObject.next = this.next.clone();
} catch (CloneNotSupportedException e) {
System.err.print("Clone not supported");
}
return newObject;
}
}
}
当我尝试克隆MyLinkedList时,我得到java.lang.StackOverflowError。我做错了什么?
答案 0 :(得分:0)
每次克隆节点时,您还要克隆其两个相邻节点。
每个节点都继续克隆他们的相邻节点,从而再次克隆原始节点。
(实际上,它首先克隆前一个节点,围绕双链表进行比赛,从不触及next
)
在解决问题时,请确保克隆的next.previous
引用原始克隆。