【发布时间】:2011-02-27 06:26:59
【问题描述】:
我正在尝试在 DoubleLinkedList 上实现 clone() 方法。现在的问题是,按照“约定”来实现它比仅仅创建一个新的DoubleLinkedList 并用我当前的 DoubleLinkedList 的所有元素填充它要麻烦得多。
这样做有什么不方便的地方吗?
这是我目前的做法:
@Override
public DoubleLinkedList<T> clone() {
DoubleLinkedList<T> dll = new DoubleLinkedList<T>();
for (T element : dll) {
dll.add(element);
}
return dll;
}
这是约定俗成的内容:
@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());
}
}
【问题讨论】: