package p351;
public class TestClone implements Cloneable {
private int a = 5;
private int b[];
public TestClone() {
b = new int[5];
b[0] = 3;
}
@Override
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
public static void main(String[] args) {
System.out.println("===============a================");
TestClone t = new TestClone();
System.err.println("t.a=" + t.a);
System.err.println("t.b[0]=" + t.b[0]);
TestClone t1 = (TestClone) t.clone();
if (t1.b == t.b)
System.out.println("浅层克隆:" + "t1.b=" + t.b + " t1.b=" + t1.b);
else
System.out.println("非浅层克隆:" + "t1.b=" + t.b + " t1.b=" + t1.b);
t1.a++;
t.b[0] = 1234;
System.out.println("==============b=================");
System.err.println("t.a=" + t.a);
System.err.println("t.b[0]=" + t.b[0]);
System.err.println("t1.a=" + t1.a);
System.err.println("t1.b[0]=" + t1.b[0]);
}
}
运行结果:
===============a================
t.a=5
t.b[0]=3
t.a=5
t.b[0]=1234
t1.a=6
t1.b[0]=1234
浅层克隆:t1.b=[I@888e6c t1.b=[I@888e6c
==============b=================
package p351;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TestDeepClone implements Cloneable, Serializable {
private int a = 5;
private int b[];
public TestDeepClone() {
b = new int[5];
b[0] = 3;
}
public Object deepClone() throws IOException, ClassNotFoundException {
// 将对象写到流中
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 再从流中读出来
ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(bo.toByteArray()));
return oi.readObject();
}
public static void main(String[] args) {
System.out.println("=========Deep======a================");
TestDeepClone t = new TestDeepClone();
System.err.println("t.a=" + t.a);
System.err.println("t.b[0]=" + t.b[0]);
TestDeepClone t1 = null;
try {
t1 = (TestDeepClone) t.deepClone();
if (t1.b == t.b)
System.out.println("浅层克隆:" + "t1.b=" + t.b + " t1.b=" + t1.b);
else
System.out.println("非浅层克隆:" + "t1.b=" + t.b + " t1.b=" + t1.b);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.a++;
t.b[0] = 1234;
t1.b[0] = 2222;
System.out.println("==============b=================");
System.err.println("t.a=" + t.a);
System.err.println("t.b[0]=" + t.b[0]);
System.err.println("t1.a=" + t1.a);
System.err.println("t1.b[0]=" + t1.b[0]);
}
}
运行结果:
=========Deep======a================
t.a=5
t.b[0]=3
非浅层克隆:t1.b=[I@1829e6f t1.b=[I@180f96c
==============b=================
t.a=5
t.b[0]=1234
t1.a=6
t1.b[0]=2222