覆盖泛型 SinglyLinkedList 中的 clone() 方法 class

Override the clone() method in generic SinglyLinkedList class

覆盖克隆方法

当我尝试覆盖通用 SinglyLinkedList class 中的 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()可能return一个对象,所以,我的问题是代码是否应该重写为:

Node<E> newest = new Node<>(walk.getElement().clone(), null);

是否可能存在 CloneNotSupportedException?我是新来的Java~ 提前致谢!

不太确定你在问什么 - 因为答案似乎太明显了。

发布的代码克隆了结构而不是结构中的对象。如果您也想克隆对象,则必须将所有 getElement() 调用替换为 getElement().clone().