浅拷贝将原来对象的内存地址复制给一个新的对象,但不创建新的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
------------------