Java中的Shallow Clone和Deep Clone

shallow clone 和 deep clone 是java clone中的两种方法

shallow clone: 被clone的对象所有的变量和原来对象一样,但是对其他对象的引用依然指向原来的对象。

deep clone   : 被clone的对象所有的变量和原来对象一样,对其他对象的引用指向新创建的对象。

 

 

首先,需要实现java Cloneable接口,然后 override clone()方法。

Shallow Clone的一个例子:

Tyre.java(自行车轮胎 ) :

public class Tyre {
       
        public int size ;
       
        public Tyre(int mySize)
       {
               this.size = mySize;
       }
}

 

 

Bike.java :

public class Bike implements Cloneable{
       
        public Tyre frontTyre ;
        public Tyre backTyre ;
       
        public Bike (Tyre front, Tyre back)
       {
               this.frontTyre = front;
               this.backTyre   = back;
       }
       
        @Override
        public Object clone() throws CloneNotSupportedException
       {
               return super .clone();   
       }
 
}

 

Main 函数:
public static void main(String[] args) throws Exception
       {
              Tyre frontTyre = new Tyre(34);
              Tyre backTyre  = new Tyre(36);
              Bike myBike = new Bike(frontTyre, backTyre);
              Bike myCopyBike = (Bike)myBike.clone();
              
              myBike. backTyre. size = 30;
              
              System. out.println("my Copy Bike's backTyre size is : "+myCopyBike .backTyre .size );
       }

 

输出结果: 30

可以理解为,myBike myCopy 共用两个车轮,当 myBike的后车轮的 size改为 30后, myCopyBike的后车轮的 size也就变成了 30.

 

Deep Clone的一个例子:

Tyre.java(自行车轮胎 ) :

public class Tyre implements Cloneable{
       
        public int size ;
       
        public Tyre(int mySize)
       {
               this.size = mySize;
       }
       
        @Override
        public Object clone() throws CloneNotSupportedException
       {
               return super .clone();
       }
}

 

Bike.java :  (修改了clone 方法)

public class Bike implements Cloneable {
       
        public Tyre frontTyre ;
        public Tyre backTyre ;
       
        public Bike (Tyre front, Tyre back)
       {
               this.frontTyre = front;
               this.backTyre   = back;
       }
       
        @Override
        public Object clone() throws CloneNotSupportedException
       {
               Bike bike = (Bike )super .clone();
              bike. frontTyre = (Tyre)this .frontTyre .clone();
              bike. backTyre  = (Tyre) this.backTyre .clone();
               return bike;
       }
}

 

Main函数:

public static void main(String[] args) throws Exception
{
       Tyre frontTyre = new Tyre(34);
       Tyre backTyre  = new Tyre(36);
       Bike myBike = new Bike (frontTyre, backTyre);
       Bike myCopyBike = (Bike)myBike.clone();
              
       myBike. backTyre. size = 30;
              
       System. out.println("my Copy Bike's backTyre size is :       "+myCopyBike.backTyre.size);
}

 

输出结果: 36

posted @ 2014-04-10 23:28  Rambot  阅读(478)  评论(0编辑  收藏  举报