Principles

  1. If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone
  2. In practice, a class that implements Cloneable is expected to provide a properly

    functioning public clone method.

  3. Never make the client do anything the library can do for the client.
  4. 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

  1. Like a constructor, a clonemethod should not invoke any nonfinal methods on the clone under construction (Item 17).
  2. 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.
  3. To make a thread-safe class implement Cloneable you must ensure its clone method be synchronized just like other methods.
  4. Class which implement Cloneable should override clone with public method return itself.
    1. First call super.clone.
    2. Fix any fields that is not primitive or immutable type object.
      1. Call the field's clone method recursively.
      2. 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.
  5. 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.
    1. Public Yum(Yum yum);
    2. Public static Yum newInstance(Yum yum);

Effective Java 11 Override clone judiciously的更多相关文章

  1. Effective Java —— 谨慎覆盖clone

    本文参考 本篇文章参考自<Effective Java>第三版第十三条"Always override toString",在<阿里巴巴Java开发手册>中 ...

  2. Effective Java 41 Use overloading judiciously

    The choice of which overloading to invoke is made at compile time. // Broken! - What does this progr ...

  3. Effective Java 42 Use varargs judiciously

    Implementation theory The varargs facility works by first creating an array whose size is the number ...

  4. Effective Java 74 Implement Serializable judiciously

    Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...

  5. 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 ...

  6. 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法

    Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. Effective Java 第三版——13. 谨慎地重写 clone 方法

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. 微软IIS对http keep-alive的“霸道”处理

    大家都知道在IIS中有个HTTP keep-alive设置,见下图: 很多人可能和我们一样,以为这样设置后,IIS会就在发送响应内容时加上这个http header——Connection: keep ...

  2. Eclipse魔法堂:修改主题

    一.前言 习惯黑色主题,而Eclipse默认的白底主题显然不是我的菜,下面一起来修改主题吧! 二.主题资源 Eclipse Color Themes(http://eclipsecolorthemes ...

  3. JS魔法堂:那些困扰你的DOM集合类型

    一.前言 大家先看看下面的js,猜猜结果会怎样吧! 可选答案: ①. 获取id属性值为id的节点元素 ②. 抛namedItem is undefined的异常 var nodes = documen ...

  4. BAT及各大互联网公司前端笔试面试题--Html,Css篇

    注意 转载须保留原文链接(http://www.cnblogs.com/wzhiq896/p/5931347.html )作者:wangwen896 整理分享出来希望更多的前端er共同进步吧,不仅适用 ...

  5. Logger.getLogger和LogFactory.getLog的区别

    Logger来自log4j自己的包.如果用Logger.getLogger,需要一个log4j的jar包,用此方式你只能依靠log4j: LogFactory来自common-logging包.如果用 ...

  6. Linux平台Qt creator报错:Circular all <- first dependency dropped

    在Linux下安装好Qt 5.0之后,使用Qt Creator创建了一个基于QMainWindow的框架程序.原本应该可以顺利的完成编译工作,因为自带的模板工程没有经过任何修改.可是在编译整个工程的时 ...

  7. easyui-treegrid节点选择

    easyui-treegrid本身不能实现选中父节点子节点全选,必须通过另外的方法来实现,这里说下如何通过修改节点样式添加checkbox来实现级联选择效果 首先需要格式化节点的样式 formatte ...

  8. Javascript语法去控制Web控件的Enabled属性

    Web控件当使用Enabled属性时,它生成html之后会变成了disabled了.我们为了能够在javascript去控制控件的禁用与启用,得从这个disabled入手.如:

  9. las数据集加载las数据

    引用的类库:ESRI.ArcGIS.GeoDatabaseExtensions 逻辑步骤: 1.创建las数据集(ILasDataset). 2.实例化las数据集的编辑器(ILasDatasetEd ...

  10. 小巧方便的MVC后端验证码,供大家学习借鉴

    调用: public ActionResult Vcode()//验证码 { string code = ValidateCode.CreateRandomCode(4); ValidateCode. ...