Implementing clone on a LinkedList

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-06-03T11:21:18Z Indexed on 2010/06/03 11:24 UTC
Read the original article Hit count: 211

Filed under:
|
|

I am trying to implement a clone() method on a DoubleLinkedList. Now, the problem is that implementing it by "the convention" is a lot more troublesome than just creating a new DoubleLinkedList and filling it with all the elements of my current DoubleLinkedList.

Is there any inconvenient I am not seeing when doing that?

Here is my current approach:

@Override
public DoubleLinkedList<T> clone() {
    DoubleLinkedList<T> dll = new DoubleLinkedList<T>();

    for (T element : dll) {
        dll.add(element);
    }

    return dll;
}

Here is what it would be by the convention:

@Override
public DoubleLinkedList<T> clone() {
            try {
            DoubleLinkedList<T> dll = (DoubleLinkedList<T>)super.clone();
               //kinda complex code to copy elements
               return dll;
    } catch (CloneNotSupportedException e) {
                throw new InternalError(e.toString());
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about cloning