Effective Java 11 Override clone judiciously
Principles
- If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone
- In practice, a class that implements Cloneable is expected to provide a properly
functioning public clone method.
- Never make the client do anything the library can do for the client.
- The clone architecture is incompatible with normal use of final fields referring to mutable objects
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression
x.clone() != x will be true,
x.clone().getClass() == x.getClass() will be true,
but these are not absolute requirements. While it is typically the case that
x.clone().equals(x) will be true,
this is not an absolute requirement. Copying an object will typically entail creating a new instance of its class, but it may require copying of internal data structures as well. No constructors are called.
The return type of the method is subclass instead of the super class which means this is applied with covariant which is introduced from JRE 1.5. As the code shown below:
@Override public PhoneNumber clone() {
try {
return (PhoneNumber) super.clone();
} catch(CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}
}
import java.util.Arrays;
import java.util.EmptyStackException;
public class Stack implements Cloneable {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
this.elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
// Ensure space for at least one more element.
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
@Override
protected Object clone() throws CloneNotSupportedException {
try {
Stack result = (Stack) super.clone();
// Do recursive clone with a class.
result.elements = elements.clone();
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
Implement clone with recursive clone method.
public class Hashtable implements Cloneable {
private Entry[] buckets = new Entry[3];
private static class Entry {
final Object key;
Object value;
Entry next;
Entry(Object key, Object value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
// Recursively copy the linked list headed by this Entry
Entry deepCopy() {
return new Entry(key, value, next == null ? null : next.deepCopy());
}
@Override
public String toString() {
return String.format("[key: %d, value: %s, next: %s]", key, value,
next);
}
}
public static void main(String[] args) {
Hashtable ht = new Hashtable();
Entry previous = null;
for (int i = 0; i < 3; i++) {
Entry e = new Entry(i, "v" + i, previous);
ht.buckets[i] = e;
}
Hashtable newHt = ht.clone();
newHt.buckets[newHt.buckets.length - 1] = new Entry(
newHt.buckets[newHt.buckets.length - 1].key,
newHt.buckets[newHt.buckets.length - 1].value
+ String.valueOf(1),
newHt.buckets[newHt.buckets.length - 1].next);
System.out.println("newHt");
for (int i = 0; i < newHt.buckets.length; i++) {
System.out.println(newHt.buckets[i]);
}
System.out.println("ht");
for (int i = 0; i < ht.buckets.length; i++) {
System.out.println(ht.buckets[i]);
}
}
@Override
public Hashtable clone() {
try {
Hashtable result = (Hashtable) super.clone();
result.buckets = new Entry[buckets.length];
for (int i = 0; i < buckets.length; i++)
if (buckets[i] != null)
result.buckets[i] = buckets[i].deepCopy();
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
To prevent a stack overflow caused by the lengthy stack frame for each element in the list from happening. We can implement the code like this below:
// Iteratively copy the linked list headed by this Entry
Entry deepCopy() {
Entry result = new Entry(key, value, next);
for (Entry p = result; p.next != null; p = p.next)
p.next = new Entry(p.next.key, p.next.value, p.next.next);
return result;
}
Summary
- Like a constructor, a clonemethod should not invoke any nonfinal methods on the clone under construction (Item 17).
- Object's clone method is declared to throw CloneNotSupportedException, but overriding clone methods can omit this declaration. But if the subclass overrides its superclass's clone method it should be declared as proteteced and throw CloneNotSupportedException and the class should not implment Cloneable.
- To make a thread-safe class implement Cloneable you must ensure its clone method be synchronized just like other methods.
- Class which implement Cloneable should override clone with public method return itself.
- First call super.clone.
- Fix any fields that is not primitive or immutable type object.
- Call the field's clone method recursively.
- Handle the exception case that if the object represent a unique ID or serial number or creating time even if they are primitive type or a reference to immutable object.
- If it's not appropriate way to provide an alternative means of object coping or simply not providing the capability of cloneable(such as immutable class) then just provide a copy constructor or copy factory.
- Public Yum(Yum yum);
- Public static Yum newInstance(Yum yum);
Effective Java 11 Override clone judiciously的更多相关文章
- Effective Java —— 谨慎覆盖clone
本文参考 本篇文章参考自<Effective Java>第三版第十三条"Always override toString",在<阿里巴巴Java开发手册>中 ...
- Effective Java 41 Use overloading judiciously
The choice of which overloading to invoke is made at compile time. // Broken! - What does this progr ...
- Effective Java 42 Use varargs judiciously
Implementation theory The varargs facility works by first creating an array whose size is the number ...
- Effective Java 74 Implement Serializable judiciously
Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法
Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第三版——13. 谨慎地重写 clone 方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- Android 学习笔记之AndBase框架学习(四) 使用封装好的函数实现单,多线程任务
PS:Force Is Meaningless Without Skill 学习内容: 1.使用AndBase实现单线程任务... 2.使用AndBase实现多线程任务... AndBase内部封 ...
- 最近一段时间开发客户端app的感悟
关于android和cocos2d 凭着对大学时候写html+css的一点点的记忆,我还是认为android的布局xml文件还是参考了html+css,只是他更加臃肿!就想 android平台本身那样 ...
- for循环的嵌套,for循环的穷举迭代
for循环的嵌套 输入一个正整数,求阶乘的和 嵌套 Console.Write("请输入一个正整数:"); int ...
- 自学silverlight 5.0
这是一个silverlight游戏:http://keleyi.com/keleyi/phtml/silverlight/ 接了个单子,非要用Silverlight 5来作一个项目,之前从来没接触过这 ...
- BI之SSAS完整实战教程4 -- 部署至SSAS进行简单分析
上一篇已经创建了多维数据集的结构. 接下来我们将多维数据集的架构定义发送到Analysis Services实例,部署到AS上去. 文章提纲 部署和浏览多维数据集 SSMS使用简介 总结 一.部署和浏 ...
- javascript的 == 与 === 的区别
1.对于基础类型,例如string,number ==和===是有区别的 1)不同类型间比较,==之比较“转化成同一类型后的值”看“值”是否相等,===如果类型不同,其结果就是不等 2)同类型比较,直 ...
- 泛函编程(12)-数据流-Stream
在前面的章节中我们介绍了List,也讨论了List的数据结构和操作函数.List这个东西从外表看上去挺美,但在现实中使用起来却可能很不实在.为什么?有两方面:其一,我们可以发现所有List的操作都是在 ...
- oracle sql 语句优化
(1)选择最有效率的表名顺序(只在基于规则的优化器中有效):Oracle的解析器按照从右到左的顺序处理FROM子句中的表名,FROM子句中写在最后的表(基础表 driving table)将被最先处理 ...
- Represent code in math equations
Introduce The article shows a way to use math equations to represent code's logical. Key ideas logic ...
- html button自动提交表单问题
在ie中,button默认的type是button,而其他浏览器和W3C标准中button默认的属性都是submit,所以在chrome中,需要使用<button type="butt ...