【发布时间】:2015-06-24 09:48:39
【问题描述】:
覆盖克隆方法
当我尝试覆盖通用 SinglyLinkedList 类中的 clone() 方法以获取深度克隆时,我遇到了以下代码。事实上,我对代码有点困惑。 如下图:
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;
}
元素的定义:
E element;
public E getElement() {
return element;
}
因为它是泛型类型,这意味着 getElement() 可能返回一个对象,所以,我的问题是代码是否应该重写为:
Node<E> newest = new Node<>(walk.getElement().clone(), null);
是否可能存在 CloneNotSupportedException?我是Java新手~ 提前致谢!
【问题讨论】:
-
这两行是一样的...应该是一样的吗?
-
Kent Pitman(ANSI Common Lisp 标准的编辑之一)写了一篇关于这个主题的short essay(虽然是从 Lisp 的角度来看,但这里的概念也适用)。阅读标题“复制”部分。列表类的作者做出了(有点)武断的决定;我碰巧同意这里的决定,但它仍然是任意的。另外:默认情况下,对象是不可克隆的,所以什么都没有,通用容器可以调用来克隆对象,除非类型参数
E以某种方式限制为提供此功能的类
标签: java generics linked-list clone adt