Java 重写泛型SinglyLinkedList类中的clone()方法 重写克隆方法
当我试图重写泛型SinglyLinkedList类中的clone()方法以获得深度克隆时,我遇到了以下代码。事实上,我对代码有点困惑。 见下文:Java 重写泛型SinglyLinkedList类中的clone()方法 重写克隆方法,java,generics,linked-list,clone,adt,Java,Generics,Linked List,Clone,Adt,当我试图重写泛型SinglyLinkedList类中的clone()方法以获得深度克隆时,我遇到了以下代码。事实上,我对代码有点困惑。 见下文: public SinglyLinkedList<E> clone() throws CloneNotSupportedException { // use inherited Object.clone() to create the initial copy SinglyLinkedList<E> other
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// use inherited Object.clone() to create the initial copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone( ); // safe cast
if (size > 0) {
// we need independent chain of nodes
other.head = new Node<>(head.getElement( ), null);//Seems something wrong.
Node<E> walk = head.getNext( ); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) {
// make a new node storing same element
Node<E> newest = new Node<>(walk.getElement( ), null);//So as this one
otherTail.setNext(newest);
// link previous node to this one
otherTail = newest;
walk = walk.getNext( );
}
}
return other;
}
由于它是泛型类型,这意味着getElement()可能会返回一个对象,因此,我的问题是是否应该将代码重写为:
Node<E> newest = new Node<>(walk.getElement().clone(), null);
Node newest=新节点(walk.getElement().clone(),null);
是否可能存在CloneNotSupportedException?我是Java新手~
提前谢谢 不太清楚你在问什么——因为答案似乎太明显了
发布的代码克隆结构,但不克隆结构中的对象。如果您也想克隆对象,则必须将所有
getElement()
调用替换为getElement().clone()
这两行是相同的。。。应该是吗?Kent Pitman(ANSI Common Lisp标准的编辑之一)写了一篇关于这个主题的文章(虽然是从Lisp的角度,但概念也适用于这里)。阅读标题为“复制”的部分。list类的作者做出了(某种程度上)武断的决定;我碰巧同意这里的决定,但它仍然是武断的。另外:默认情况下对象是不可克隆的,因此没有任何东西,通用容器可以调用来克隆对象,除非类型参数E
以某种方式限制为类,这提供了此功能。其目的是制作深度副本而不是卷影副本。事实上,我是从书中得到代码的,所以我有点不明白。@shady-这个示例正在执行一个浅层克隆。深度克隆也应该像我建议的那样克隆所有元素。。。因此,我们在代码的第5行创建一个新的头节点,然后在为新列表创建和链接新节点的同时,遍历原始列表的其余部分(第8-13行)。这是一个浅层克隆,仅创建新节点。
Node<E> newest = new Node<>(walk.getElement().clone(), null);