(Entry
}
t.keySet = null;
t.entrySet = null;
t.values = null;
t.modCount = 0;
return t;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}注意,递归调用实例变量.clone()时,如果该变量为final,则不行!clone架构与饮用可变对象的final域的正常用法是不兼容的!
另一个实现对象拷贝的好办法是提供一个拷贝构造器(copy constructor)或者拷贝工厂(copy factory)。
例如:
[java]
public Yum(Yum yum);
public static Yum newInstance(Yum yum);
public Yum(Yum yum);
public static Yum newInstance(Yum yum);
这种方法比clone有更多优势:
不依赖于某一种有风险的、语言之外的对象创建机制
不要求遵守尚未制定好文档的规范
不会与final域的正常使用发生冲突
不会抛出不必要的受检异常
不需要进行类型转换
另外,拷贝构造器和拷贝工厂可以带参数,参数类型一般是该类实现的接口,以便用户选择拷贝的实现类型。
例如,有一个HashSet s,希望把它拷贝成一个TreeSet,可以调用:new TreeSet(s)
[java]
/**
* Constructs a new tree set containing the elements in the specified
* collection, sorted according to the natural ordering of its
* elements. All elements inserted into the set must implement the
* {@link Comparable} interface. Furthermore, all such elements must be
* mutually comparable: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set.
*
* @param c collection whose elements will comprise the new set
* @throws ClassCastException if the elements in {@code c} are
* not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException if the specified collection is null
*/
public TreeSet(Collection< extends E> c) {
this();
addAll(c);
}
/**
* Constructs a new tree set containing the elements in the specified
* collection, sorted according to the natural ordering of its
* elements. All elements inserted into the set must implement the
* {@link Comparable} interface. Furthermore, all such elements must be
* mutually comparable: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set.
*
* @param c collection whose elements will comprise the new set
* @throws ClassCastException if the elements in {@code c} are
* not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException if the specified collection is null
*/
public TreeSet(Collection< extends E> c) {
this();
addAll(c);
}