@XQF
2017-02-15T09:44:48.000000Z
字数 2076
阅读 1327
java
情况的契机在于我们要保留一个当前对象的状态。要是直接使用则是简单的引用传递而已,改变热河一个引用指向的对象值,改变都会同步。
使用clone方法的步骤
class T implements Cloneable {
private int a;
public void setA(int a) {
this.a = a;
}
public int getA() {
return a;
}
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
public class Test {
public static void main(String[] args) {
T t1 = new T();
t1.setA(1);
T t2 = t1;
System.out.println("简单引用修改前");
System.out.println(t1.getA());
System.out.println(t2.getA());
System.out.println();
System.out.println("简单引用修改后");
t2.setA(2);
System.out.println(t1.getA());
System.out.println(t2.getA());
T t3 = (T) t2.clone();
System.out.println("clone后数值修改前");
System.out.println(t2.getA());
System.out.println(t3.getA());
System.out.println();
t3.setA(3);
System.out.println("clone后数值修改前");
System.out.println(t2.getA());
System.out.println(t3.getA());
}
}
测试好像String类型也可以
class T implements Cloneable {
private String str;
public String getString() {
return str;
}
public void setString(String str) {
this.str = str;
}
public Object clone() {
T o = null;
try {
o = (T) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
public class Test {
public static void main(String[] args) {
T t1 = new T();
t1.setString("hehhe");
T t2 = (T) t1.clone();
t1.setString("XXXXX");
System.out.println(t1.getString());
System.out.println(t2.getString());
}
}
深复制与浅复制在代码上的区别是要是该对象内部含有非基本类型对象的话,还要把非基本类型对象复制一遍
o.attr=this.getAttr().clone()
class T implements Cloneable {
private Date d = new Date();
public Date getDate() {
return d;
}
public void setDate(Date d) {
this.d = d;
}
public Object clone() {
T o = null;
try {
o = (T) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.d = (Date) getDate().clone();
return o;
}
}
public class Test {
public static void main(String[] args) {
T t = new T();
T t1 = (T) t.clone();
T t2 = t1;
System.out.println(t);
System.out.println(t1);
System.out.println(t2);
}
}
com.leetcode.xqf.T@131245a
com.leetcode.xqf.T@16f6e28
com.leetcode.xqf.T@16f6e28
查到这个Date类是实现了Cloneable接口的。
浅复制只是复制当前对象的引用对象
深复制全部复制个遍