<span style="font-family: Arial, Helvetica, sans-serif;">浅克隆:</span>
克隆得到的对象B跟原始对象A对比:A对象中属性的值相等,且A中对象B中对象是同一个对象,及内存地址为相同。
换言之:浅克隆只是把需要复制的对象的值复制了一遍,但关于其引用的其他对象只是复制了内存地址。
深克隆:
克隆得到的对象跟原始对象中所有属性和对象的值相等。且内存地址不同。
换言之:深复制把要复制的对象所引用的对象都复制了一遍。
举例说明:
package com.clone;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class User implements Serializable,Cloneable{
/**
* 序列化版本号
*/
private static final long serialVersionUID = 1L;
protected User user;
protected String id;
protected String name;
protected String phone;
protected Integer x;
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Object deepClone() throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
new ObjectOutputStream(bo).writeObject(this);
return new ObjectInputStream(new ByteArrayInputStream(bo.toByteArray())).readObject();
}
}
package com.clone;
public class Test {
public static void main(String[] args) {
User u = new User();
u.setId("sdsdsdaxzsdsdeqebd");
u.setName("张三丰");
u.setPhone("110");
u.setX(10);
User u4 = new User();
u4.setId("22");
u4.setName("22");
u4.setPhone("22");
u.setUser(u4);
try {
System.out.println("=============浅克隆=============");
User u2 = (User) u.clone();
System.out.println(u2.getId());
System.out.println(u2.getName());
System.out.println(u2.getPhone());
System.out.println(u2.getUser().getPhone());
System.out.println("u2.getUser() == u.getUser() ? " + (u2.getUser() == u.getUser()));
u2.getUser().setId("111111111111111");
u2.setId("xxxxxxxxxxxxxxxxxxxxx");
System.out.println(u.getUser().getId());
System.out.println(u.getId());
System.out.println();
System.out.println("=============深克隆=============");
User u3 = (User) u.deepClone();
System.out.println(u3.getId());
System.out.println(u3.getName());
System.out.println(u3.getPhone());
System.out.println(u3.getUser().getPhone());
System.out.println("u3.getUser() == u.getUser() ? " + (u3.getUser() == u.getUser()));
u3.getUser().setId("3333333333333");
System.out.println(u.getUser().getId());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果:
=============浅克隆=============
sdsdsdaxzsdsdeqebd
张三丰
110
22
u2.getUser() == u.getUser() ? true
111111111111111
sdsdsdaxzsdsdeqebd
=============深克隆=============
sdsdsdaxzsdsdeqebd
张三丰
110
22
u3.getUser() == u.getUser() ? false
111111111111111