Effective Java 英文 第二版 读书笔记 Item 11:Override clone judiciously

本文探讨了深复制的概念及实现方式,详细分析了在Java中使用Clone方法时可能遇到的问题,并提出了解决方案。文章还介绍了替代方法,如使用复制构造函数或复制工厂等。

x.clone()!=x will be true

x.clone().getClass()==x.getClass() will be true

x.clone().equals(x) always true.

意味着深复制,新建对象,数据与结构与原对象一致,

Copying an object will typically entail creating a new instance of tis class,but it may require copying of internal data structures as well.

 

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.

 

这样的类直接调用super.clone()后,会造成elements指向同一个数组对象

 

correct

 

In effect the clone method functions as another constructor;you must ensure that it does no harm to the original object and that

it properly established invariants on the clone.

 

the clone architecture is incompatible with normal use of final fields referring to mutable objects,

问题出在clone之后的next引用的是原来数据的next entry,做法就是我们需要更新copy的时候把新数据的next也传入来赋值一下

Though the clone has its own bucket array ,thsi array references the same linked lists as the original,

which can easily cause nondeterministic behavior in both the clone and the original.

 

A fine approach to object copying is to provide a copy constructor or copyfactory.

A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor

for example,
    public Yum(Yum yum);
A copy factory is the static factory analog of a copy constructor:
    public static Yum newInstance(Yum yum);

转载于:https://www.cnblogs.com/linkarl/p/5578666.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值