Chinaunix首页 | 论坛 | 博客
  • 博客访问: 497936
  • 博文数量: 99
  • 博客积分: 2030
  • 博客等级: 大尉
  • 技术积分: 783
  • 用 户 组: 普通用户
  • 注册时间: 2006-08-12 09:11
文章分类

全部博文(99)

文章存档

2023年(2)

2022年(1)

2020年(1)

2019年(1)

2018年(4)

2017年(16)

2016年(60)

2015年(1)

2013年(3)

2006年(10)

我的朋友

分类: Java

2016-03-31 22:08:44

转载请注明出处:http://blog.csdn.net/mazhimazh/article/details/16828505

在使用克隆时,我们需要知道使用的目的:就是为了快速构造一个和已有对象相同的副本。如果克隆对象,一般需要先创建一个对象,然后将原对象中的数据导入到新创建的对象中去,而不用根据已有对象进行手动赋值操作。

1、克隆方法clone()


clone是定义一个Object类下基本方法之一,可以说,任何克隆的过程最终都将到达java.lang.Object 的clone()方法,而其在Object接口中定义如下:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. protected native Object clone() throws CloneNotSupportedException;  

有如下3点需要提示:

      (1)他是一个protected修饰的native方法,因此它的实现是取决于本地代码。native方法的效率一般来说都是远高于java中的非native方法。

      (2)Object中的clone方法是protected的,所以要使用clone就必须继承Object类(默认)。并且为了可以使其它类调用该方法,覆写克隆方法时必须将其作用域设置为public.

      (3)克隆方法返回的是一个Object对象,所以必须要经过强制类型转换。

       通常克隆对象都是通过调用super.clone()方法来获取克隆对象的,所以任何克隆的过程最终都将到达java.lang.Object 的clone()方法。但是在覆写clone()方法时,这个类需要继承Clonable接口,这个接口中没有定义方法,他类似于RandomAccess这些接口类,只做为一种标识存在。如果 clone 类没有实现 Cloneable 接口,并调用了 Object 的 clone() 方法(也就是调用了 super.Clone() 方法),那么Object 的 clone() 方法就会抛出 CloneNotSupportedException 异常。


通过从源码的注释中可以看出,克隆的一些特性:

(1)x.clone() != x 必须为真,也就是对于基础类型来说,其克隆后在堆中有两个独立且内容相同的内存区域。而对于引用类型来说,其引用也不相同。也就是说克隆对象和原始对象在java 堆(heap)中是两个独立的对

(2)x.clone().getClass() == x.getClass()  他们所属的类是同一个

(3) x.clone().equals(x)   所比较的对象内容相同

从上述的第二和第三点可以看出,克隆完全是拷贝一个独立的副本到内存中。但是由于克隆方法可以覆写,所以并不能保证克隆出来的对象能够达到(2)和(3)要求的标准,所以他们不是克隆方法所必须要求的。


2、浅克隆与深克隆

   

      克隆就是复制一个对象的复本.但一个对象中可能有基本数据类型,如:int,long,float等,也同时含有对象数据类型如(数组,集合等)。被克隆得到的对象基本类型的值修改了,原对象的值不会改变.这种适合shadow clone(浅克隆).

   但如果你要改变一个非基本类型的值时,原对象的值却改变了,.比如一个数组,内存中只copy他的地址,而这个地址指向的值并没有 copy,当clone时,两个地址指向了一个值,这样一旦这个值改变了,原来的值当然也变了,因为他们共用一个值.,这就必须得用深克隆(deep clone)


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public class ShadowClone implements Cloneable{  
  2.          
  3.     private int a;   // 基本类型  
  4.     private int[] b; // 非基本类型  
  5.     // 重写Object.clone()方法,并把protected改为public  
  6.     @Override  
  7.     public Object clone(){  
  8.         ShadowClone sc = null;  
  9.         try  
  10.         {  
  11.             sc = (ShadowClone) super.clone();  
  12.         } catch (CloneNotSupportedException e){  
  13.             e.printStackTrace();  
  14.         }  
  15.         return sc;  
  16.     }  
  17.     public int getA()  
  18.     {  
  19.         return a;  
  20.     }  
  21.     public void setA(int a)  
  22.     {  
  23.         this.a = a;  
  24.     }  
  25.     public int[] getB() {  
  26.     return b;  
  27.     }  
  28.     public void setB(int[] b) {  
  29.     this.b = b;  
  30.     }    
  31. }  


然后进行测试:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public class Test{  
  2.     public static void main(String[] args) throws CloneNotSupportedException{  
  3.         ShadowClone c1 = new ShadowClone();  
  4.         //对c1赋值  
  5.         c1.setA(100) ;  
  6.         c1.setB(new int[]{1000}) ;  
  7.           
  8.         System.out.println("克隆前c1:  a="+c1.getA()+" b="+c1.getB()[0]);  
  9.         //克隆出对象c2,并对c2的属性A,B,C进行修改  
  10.         ShadowClone c2 = (ShadowClone) c1.clone();  
  11.         //对c2进行修改  
  12.         c2.setA(50) ;  
  13.         int []a = c2.getB() ;  
  14.         a[0]=500 ;  
  15.         c2.setB(a);  
  16.         System.out.println("克隆前c1:  a="+c1.getA()+" b="+c1.getB()[0]);  
  17.         System.out.println("克隆后c2:  a="+c2.getA()+ " b[0]="+c2.getB()[0]);  
  18.     }  
  19. }  
结果为:


克隆前c1:  a=100 b=1000
克隆前c1:  a=100 b=500
克隆后c2:  a=50 b[0]=500

可以看出,基本类型可以使用浅克隆,而对于引用类型,由于引用的是内容相同,所以改变c2实例对象中的属性就会影响到c1。所以引用类型需要使用深克隆。另外,在开发一个不可变类的时候,如果这个不可变类中成员有引用类型,则就需要通过深克隆来达到不可变的目的。



3、覆写clone方法深克隆




[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. class bottle implements Cloneable {  
  2.     public wine wn;  
  3.   
  4.     public bottle() {  
  5.     }  
  6.   
  7.     public bottle(wine wn) {  
  8.         this.wn = wn;  
  9.     }  
  10.     // 覆写clone()方法  
  11.     protected Object clone() throws CloneNotSupportedException {  
  12.         bottle newBtl = (bottle) super.clone();  
  13.         return newBtl;  
  14.     }  
  15. }  
  16.   
  17. class wine {  
  18.     int degree;       
  19.     public int getDegree() {  
  20.         return degree;  
  21.     }  
  22.     public void setDegree(int degree) {  
  23.         this.degree = degree;  
  24.     }  
  25. }  
  26.   
  27. public class test04 {  
  28.     public static void main(String[] args) throws CloneNotSupportedException {  
  29.           
  30.         bottle bottle = new bottle(new wine());  
  31.         bottle bottle1 = (bottle) bottle.clone();  
  32.           
  33.         System.out.println("bottle1.wine : " + bottle1.wn.getDegree() );  
  34.         bottle1.wn.setDegree(100);  
  35.           
  36.         System.out.println("bottle1.wine : " + bottle1.wn.getDegree() );  
  37.         System.out.println("bottle.wine : " + bottle.wn.getDegree());  
  38.     }  
  39. }  
结果如下:


bottle1.wine : 0
bottle1.wine : 100
bottle.wine : 100

这就是浅克隆造成的问题,下面使用clone()来进行深拷贝:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. class bottle implements Cloneable {  
  2.     public wine wn;  
  3.   
  4.     public bottle(wine wn) {  
  5.         this.wn = wn;  
  6.     }  
  7.     // 覆写clone()方法  
  8.     protected Object clone() throws CloneNotSupportedException {  
  9.         bottle newBtl = (bottle) super.clone();  
  10.         newBtl.wn = (wine) wn.clone();  
  11.         return newBtl;  
  12.     }  
  13. }  
  14.   
  15. class wine implements Cloneable {  
  16.     int degree;       
  17.     public int getDegree() {  
  18.         return degree;  
  19.     }  
  20.     public void setDegree(int degree) {  
  21.         this.degree = degree;  
  22.     }  
  23.     // 覆写clone()方法  
  24.     protected Object clone() throws CloneNotSupportedException {  
  25.         return super.clone();  
  26.     }  
  27. }  
结果如下:


bottle1.wine : 0
bottle1.wine : 100
bottle.wine : 0

结果进行了正确的显示。如果要在wine中还有字符串类型该怎么办?例如:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. class wine implements Cloneable {  
  2.     int degree;     
  3.     String name="法国白兰地";  
  4.       
  5.     public int getDegree() {  
  6.         return degree;  
  7.     }  
  8.     public void setDegree(int degree) {  
  9.         this.degree = degree;  
  10.     }  
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.     public void setName(String name) {  
  15.         this.name = name;  
  16.     }  
  17.     // 覆写clone()方法  
  18.     protected Object clone() throws CloneNotSupportedException {  
  19.         return super.clone();  
  20.     }  
  21. }  
测试程序如下:



[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. bottle bottle = new bottle(new wine());  
  2.         bottle bottle1 = (bottle) bottle.clone();  
  3.           
  4.         System.out.println("bottle1.wine : " + bottle1.wn.getName() );  
  5.         bottle1.wn.setName("中国二锅头");  
  6.           
  7.         System.out.println("bottle1.wine : " + bottle1.wn.getName() );  
  8.         System.out.println("bottle.wine : " + bottle.wn.getName());  
结果如下:


bottle1.wine : 法国白兰地
bottle1.wine : 中国二锅头
bottle.wine : 法国白兰地  
   为什么会是法国白兰地?

单独对wine进行测试:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. wine wn=new wine();  
  2.         wn.setName("法国葡萄酒");  
  3.         wine wn2=(wine)wn.clone();  
  4.           
  5.         System.out.println(wn.getName());  
  6.         System.out.println(wn2.getName());  
则结果如下:


法国葡萄酒
法国葡萄酒



4、使用序列化实现深克隆


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public class DeepClone implements Serializable{  
  2.     private int a;  
  3.     private int[] b;  
  4.     public int getA() {  
  5.         return a;  
  6.     }  
  7.     public void setA(int a)  
  8.     {  
  9.         this.a = a;  
  10.     }  
  11.     public int[] getB() {  
  12.         return b;  
  13.     }  
  14.     public void setB(int[] b) {  
  15.         this.b = b;  
  16.     }    
  17. }  
然后编写测试类:



[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package test2;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8.   
  9. public class Test2{  
  10.     public static void main(String[] args) throws CloneNotSupportedException{  
  11.         Test2 t = new Test2();  
  12.         DeepClone dc1 = new DeepClone();  
  13.         // 对dc1赋值  
  14.         dc1.setA(100);  
  15.         dc1.setB(new int[] { 1000 });  
  16.         System.out.println("克隆前dc1: a=" + dc1.getA()+"b[0]=" + dc1.getB()[0]);  
  17.         DeepClone dc2 = (DeepClone) t.deepClone(dc1);  
  18.         // 对c2进行修改  
  19.         dc2.setA(50);  
  20.         int[] a = dc2.getB();  
  21.         a[0] = 500;  
  22.         System.out.println("克隆后dc1: a=" + dc1.getA()+"b[0]=" + dc1.getB()[0]);  
  23.         System.out.println("克隆后dc2: a=" + dc2.getA()+"b[0]=" + dc2.getB()[0]);  
  24.     }  
  25.     // 用序列化与反序列化实现深克隆  
  26.     public Object deepClone(Object src){  
  27.         Object o = null;  
  28.         try{  
  29.             if (src != null){  
  30.                 ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  31.                 ObjectOutputStream oos = new ObjectOutputStream(baos);  
  32.                 oos.writeObject(src);  
  33.                 oos.close();  
  34.                 ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());  
  35.                 ObjectInputStream ois = new ObjectInputStream(bais);  
  36.                 o = ois.readObject();  
  37.                 ois.close();  
  38.             }  
  39.         } catch (IOException e){  
  40.             e.printStackTrace();  
  41.         } catch (ClassNotFoundException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.         return o;  
  45.     }  
  46. }  
运行后的结果如下:


克隆前dc1: a=100 b[0]=1000
克隆后dc1: a=100 b[0]=1000
克隆后dc2: a=50 b[0]=500

可以看到,两个引用所指向的对象在堆中相互独立,互不干扰,这样就实现了深度克隆。

4、总结:


  1. 克隆方法用于创建对象的拷贝,为了使用clone方法,类必须实现java.lang.Cloneable接口重写protected方法clone,如果没有实现Clonebale接口会抛出CloneNotSupportedException.
  2. 在克隆java对象的时候不会调用构造器
  3. java提供一种叫浅拷贝(shallow copy)的默认方式实现clone,创建好对象的副本后然后通过赋值拷贝内容,意味着如果你的类包含引用类型,那么原始对象和克隆都将指向相同的引用内容,这是很危险的,因为发生在可变的字段上任何改变将反应到他们所引用的共同内容上。为了避免这种情况,需要对引用的内容进行深度克隆。
  4. 按照约定,实例的克隆应该通过调用super.clone()获取,这样有助克隆对象的不变性。如:clone!=original和clone.getClass()==original.getClass(),尽管这些不是必须的
阅读(1045) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~