简而言之,我正在执行一项任务 - 自定义 LinkedList。我需要重写 Object.clone 来制作 MyLinkedList 的深层副本,但我不明白,我是否需要同时克隆 mested 和外部类?这是代码:
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。我究竟做错了什么?