Java中的clone和深度clone

2021-08-21 09:23:03 字數 3278 閱讀 5889

複製物件 or 複製引用

person p =

new person(

23,

"zhang");

person p1 = p;

system.out.println(p);

system.out.println(p1);

當person p1 = p;執行之後, 是建立了乙個新的物件嗎? 首先看列印結果:

person p =

new person(

23,

"zhang");

person p1 = (person) p.clone();

system.out.println(p);

system.out.println(p1);

深拷貝 or 淺拷貝

public

class

person

implements

cloneable

public

person

(){}

public

intgetage

()

public string getname

()

@override

protected object clone

()throws clonenotsupportedexception

}person p =

new person(

23,

"zhang");

person p1 = (person) p.clone();

string result = p.getname() == p1.getname()

? "clone是淺拷貝的" :

"clone是深拷貝的";

system.out.println(result);

覆蓋object中的clone方法, 實現深拷貝

static

class

body

implements

cloneable

public

body

(head head)

@override

protected object clone

()throws clonenotsupportedexception

}static

class

head /*implements

cloneable*/

public

head

(face face)

} public

static

void

main

(string args)

throws clonenotsupportedexception

在以上**中, 有兩個主要的類, 分別為body和face, 在body類中, 組合了乙個face物件。當對body物件進行clone時, 它組合的face物件只進行淺拷貝。列印結果可以驗證該結論:

static

class

body

implements

cloneable

public

body

(head head)

@override

protected object clone

()throws clonenotsupportedexception

}static

class

head

implements

cloneable

public

head

(face face)

@override

protected object clone

()throws clonenotsupportedexception

} public

static

void

main

(string args)

throws clonenotsupportedexception

列印結果為:

真的是深拷貝嗎

static

class

body

implements

cloneable

public

body

(head head)

@override

protected object clone

()throws clonenotsupportedexception

}static

class

head

implements

cloneable

public

head

(face face)

@override

protected object clone

()throws clonenotsupportedexception

} static

class

face

{}

public

static

void

main

(string args)

throws clonenotsupportedexception

列印結果為:

如何進行徹底的深拷貝

static

class

head

implements

cloneable

public

head

(face face)

@override

protected object clone

()throws clonenotsupportedexception

} static

class

face

implements

cloneable

}再次執行上面的示例,得到的執行結果如下:

建立徹底的深拷貝是非常麻煩的,尤其是在引用關係非常複雜的情況下, 或者在引用鏈的某一級上引用了乙個第三方的物件, 而這個物件沒有實現clone方法, 那麼在它之後的所有引用的物件都是被共享的。 舉例來說,如果被head引用的face類是第三方庫中的類,並且沒有實現cloneable介面,那麼在face之後的所有物件都會被拷貝前後的兩個body物件共同引用。假設face物件內部組合了mouth物件,並且mouth物件內部組合了tooth物件, 記憶體結構如下圖:

寫在最後

Java中的clone方法

1.功能 由方法名 轉殖 可知是複製乙個物件,方法呼叫後會建立並返回此物件的乙個副本。2.為什麼不用 以賦值的方式建立物件副本?student stu1 new student zhaoliu 18,1996 11 20 student stu2 stu1 stu2.setname lisi sys...

java中的clone 方法詳解

test public void testassign test public void testshallowcopy throws exception如果是基本資料型別的成員變數,我們轉殖之後彼此的屬性是可以相互不影響的,接著看 如果增加乙個自定義的類物件時 data public class ...

java 中的clone 在陣列中

今天在程式設計中遇到發現乙個問題,那就是二維陣列的clone,只有第一層clone了,裡層的還是指向之前的位址 string a string aa a.clone aa 0 22 system.out.println a 0 列印 1 string e string ee e.clone ee 0...