天天看點

JAVA中淺複制與深複制

1.淺複制與深複制概念

⑴淺複制(淺克隆)

被複制對象的所有變量都含有與原來的對象相同的值,而所有的對其他對象的引用仍然指向原來的對象。換言之,淺複制僅僅複制所考慮的對象,而不複制它所引用的對象。

⑵深複制(深克隆)

被複制對象的所有變量都含有與原來的對象相同的值,除去那些引用其他對象的變量。那些引用其他對象的變量将指向被複制過的新對象,而不再是原有的那些被引用的對象。換言之,深複制把要複制的對象所引用的對象都複制了一遍。

2.Java的clone()方法

⑴clone方法将對象複制了一份并傳回給調用者。一般而言,clone()方法滿足:

①對任何的對象x,都有x.clone() !=x//克隆對象與原對象不是同一個對象

②對任何的對象x,都有x.clone().getClass()= =x.getClass()//克隆對象與原對象的類型一樣

③如果對象x的equals()方法定義恰當,那麼x.clone().equals(x)應該成立。

⑵Java中對象的克隆

①為了擷取對象的一份拷貝,我們可以利用Object類的clone()方法。

②在派生類中覆寫基類的clone()方法,并聲明為public。

③在派生類的clone()方法中,調用super.clone()。

④在派生類中實作Cloneable接口。

class Student implements Cloneable

{

String name;

int age;

Student(String name,int age)

this.name=name;

this.age=age;

}

public Object clone()

Object o=null;

try

o=(Student)super.clone();//Object中的clone()識别出你要複制的是哪一個對象。

catch(CloneNotSupportedException e)

System.out.println(e.toString());

return o;

public static void main(String[] args)

Student s1=new Student("zhangsan",18);

Student s2=(Student)s1.clone();

s2.name="lisi";

s2.age=20;

System.out.println("name="+s1.name+","+"age="+s1.age);//修改學生2後,不影響學生1的值。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

對象的深複制:

public Object deepClone()

//将對象寫到流裡

ByteArrayOutoutStream bo=new ByteArrayOutputStream();

ObjectOutputStream oo=new ObjectOutputStream(bo);

oo.writeObject(this);

//從流裡讀出來

ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());

ObjectInputStream oi=new ObjectInputStream(bi);

return(oi.readObject());

---------------------