Java深拷贝和浅拷贝举例详解

浅拷贝将原来对象的内存地址复制给一个新的对象,但不创建新的object。

而深拷贝创建新的对象,并将需要拷贝的值复制到新的object里。

Example:

package CDExamples;

public class CDCollectionOwner {

	private String name;
	private CD[] myFavorites;
	
	public CDCollectionOwner() {
		name = "Fawzi";
		myFavorites = new CD[2];
		myFavorites[0] = new CD("Rolling Stones", "Exile on Main Street");
		myFavorites[1] = new CD("The Eagles", "Hotel California");
	}
	
	public CD[] getCDsReferenceCopy() {
		return myFavorites;
	}
	
	public CD[] getCDsShallowCopy() {
		CD[] copy = new CD[myFavorites.length];
		for (int i = 0; i < copy.length; i++)
			copy[i] = myFavorites[i];
		return copy;
	}
	
	public CD[] getCDsDeepCopy() {
		CD[] copy = new CD[myFavorites.length];
		for (int i = 0; i < copy.length; i++)
			copy[i] = new CD(myFavorites[i]);
		return copy;
	}
	
	public String toString(){
		String s = name + "\n";
		s += myFavorites[0] + " & " + myFavorites[1] + "\n";
		s += "------------------";
		return s;
	}
}
从上述代码不难看出深拷贝和浅拷贝的区别。

以下是该程序的driver:

public class CDDriver {

	/**
	 * Shows the use of the CD and RewritebleCD classes
	 * as well as their owners and collectors
	 */
	public static void main(String[] args) {
		System.out.println("****Regular CD ***");
		CDCollectionOwner p = new CDCollectionOwner();
		CD myFav = new CD("Barry Manilow","One Voice");
		CD[] a = p.getCDsReferenceCopy();
		a[0] = myFav;
		System.out.println("after reference copy:");
		System.out.println(p);
		CDCollectionOwner newp = new CDCollectionOwner();
		CD[] newa = newp.getCDsShallowCopy();
		newa[0] = myFav;
		System.out.println("after shallow copy:");
		System.out.println(newp);
		System.out.println("***Rewritable CD***");
		RewriteableCDCollectionOwner q = new RewriteableCDCollectionOwner();
		RewriteableCD[] b = q.getCDsShallowCopy();
		b[0].rewrite("Barry Manilow","One Voice");
		System.out.println("after shallow copy:");
		System.out.println(q);
		RewriteableCDCollectionOwner newq = new RewriteableCDCollectionOwner();
		RewriteableCD[] newb = newq.getCDsDeepCopy();
		newb[0].rewrite("Barry Manilow", "One Voice");
		System.out.println("after deep copy:");
		System.out.println(newq);
	}

}

输出为:

****Regular CD ***
after reference copy:
Fawzi
Barry Manilow:One Voice & The Eagles:Hotel California
------------------
after shallow copy:
Fawzi
Rolling Stones:Exile on Main Street & The Eagles:Hotel California
------------------
***Rewritable CD***
after shallow copy:
Fawzi
Barry Manilow:One Voice & The Eagles:Hotel California
------------------
after deep copy:
Fawzi
Rolling Stones:Exile on Main Street & The Eagles:Hotel California
------------------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值