【Java学习笔记 - 11】谨慎地覆盖clone

1、clone方法的通用约定是非常弱的
x.clone()!=x
x.clone().getClass()==x.getClass()
x.clone().equals(x)
都不是绝对的要求

2、Clone方法就是另一个构造器,你必须保证它不会伤害到原始的对象,并确保正确地创建被克隆对象中的约束条件。

3、clone架构与应用可变对象的final域的正常用法是不兼容的。

4、深度clone,典型例子HashTable

5、线程安全的类实现Cloneable接口,clone方法必须实现好同步:HashTable。

public class DeepClone { public static void main(String[] arr){ Hashtable<String, Integer> table=new Hashtable<String, Integer>(); table.put("MM", 100); Hashtable<String, Integer> copytable=(Hashtable) table.clone(); System.out.println("----------mm----------"+copytable.get("MM")); } } 总结:

(1)默认实现方式
实现了Cloneable接口的类都应该有一个公用的方法覆盖clone:

@Override public PhoneNumber clone() {
super.clone();
}
此公有方法首先调用super.clone(),然后修正任何需要修正的域(浅克隆、深度克隆)。
(2)最佳实践
实现对象的拷贝的好办法是提供一个拷贝构造器(copy constructor)或者拷贝工厂(copy factory)
相比Cloneable/clone优点:
不依赖于某一种很有风险的,语言之外的对象创建机制;
不要求遵守尚未制定好的文档规范;
不会与final域的正常使用发生冲突;
不会抛出不必要的受检查异常CloneNotSupportedException;
不需要强制进行类型转换;
建议使用最佳实践

/** * 拷贝构造器(copy constructor)或者拷贝工厂(copy factory)展示 * @author Administrator liuyang * Dec 23, 2009-12:05:00 AM */ public class GoodClone { private int type; private final String special; public GoodClone(int type, String spe) { this.type = type; this.special = spe; } /** * 拷贝构造器 * @param good */ public GoodClone(GoodClone good) { this.special = good.special; this.type = good.type; } /** * 拷贝工厂 * @param good * @return */ public static GoodClone newInstance(GoodClone good) { return new GoodClone(good.type, good.special); } public static GoodClone cloneInstance(GoodClone good) { return new GoodClone(good.type, good.special); } public static void main(String[] arr) { GoodClone entity = new GoodClone(10, "spacialGood"); GoodClone copyEd1 = GoodClone.newInstance(entity); System.out.println("----------克隆方式newInstance-----------" + (entity == copyEd1)); GoodClone copyEd2 = new GoodClone(entity); System.out.println("----------克隆方式2-----------" + (entity == copyEd2)); System.out.println("----------克隆方式1与克隆方式2-----------" + (copyEd1 == copyEd2)); } }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值