-
Java深拷贝与浅拷贝
添加时间:2013-6-16 点击量:深拷贝与浅拷贝首要的不合是对于引用变量的拷贝,浅拷贝的引用变量不仅仅是拷贝一个引用(地址).引用变量的成员也一样深拷贝。空话少说下面是两个拷贝的例子
1.浅拷贝
1 package com.LightCopy;
2
3 public class Professor implements Cloneable{
4 private String name;
5 private int age;
6
7 public String getName() {
8 return name;
9 }
10
11 public void setName(String name) {
12 this.name = name;
13 }
14
15 public int getAge() {
16 return age;
17 }
18
19 public void setAge(int age) {
20 this.age = age;
21 }
22
23 public Professor(String name, int age) {
24 this.name = name;
25 this.age = age;
26 }
27
28 @Override
29 public Object clone() {
30 Professor o=null;
31 try
32 {
33 o=(Professor) super.clone();
34 }
35 catch(CloneNotSupportedException e)
36 {
37 e.printStackTrace();
38 }
39
40 return o;
41 }
42
43 }
View Code2.深拷贝
1 package com.DeepCopy;
2
3 import com.LightCopy.Professor;
4
5 public class Student implements Cloneable {
6 private String name;
7 private int age;
8 private Professor pro;
9 public Professor getPro() {
10 return pro;
11 }
12
13 public void setPro(Professor pro) {
14 this.pro = pro;
15 }
16
17 public Student(String name, int age,Professor pro) {
18 this.name = name;
19 this.age = age;
20 this.pro=pro;
21 }
22
23 public String getName() {
24 return name;
25 }
26
27 public void setName(String name) {
28 this.name = name;
29 }
30
31 public int getAge() {
32 return age;
33 }
34
35 public void setAge(int age) {
36 this.age = age;
37 }
38
39 @Override
40 public Object clone() {
41 Student obj = null;
42 try {
43 obj = (Student) super.clone();
44 } catch (CloneNotSupportedException ex) {
45 ex.printStackTrace();
46 }
47 obj.pro=(Professor)pro.clone();
48 return obj;
49 }
50 }
View Code
容易发怒的意思就是: 别人做了蠢事, 然后我们代替他们, 表现出笨蛋的样子。—— 蔡康永