When I try to override the clone() method in the generic SinglyLinkedList class to get a deep clone, I come across the following code. The fact that I have a little confuse about the code. See as follow:
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;
}
The definition of element:
E element;
public E getElement() {
return element;
}
Since it is generic type, which means the getElement() may return an object, so, my question is should the code be rewrited as:
Node<E> newest = new Node<>(walk.getElement().clone(), null);
is there may be a CloneNotSupportedException? I am new to Java~ Thanks in advance!
Not quite sure what you are asking - as the answer seems too obvious.
The posted code clones the structure but not the objects in the structure. If you want to clone the objects too you must replace all getElement()
calls with getElement().clone()
.