61. 為什么要使用克隆鞍匾?
想對(duì)一個(gè)對(duì)象進(jìn)行處理交洗,又想保留原有的數(shù)據(jù)進(jìn)行接下來(lái)的操作,就需要克隆了橡淑,Java語(yǔ)言中克隆針對(duì)的是類的實(shí)例构拳。
62. 如何實(shí)現(xiàn)對(duì)象克隆梁棠?
有兩種方式:
- 實(shí)現(xiàn)Cloneable接口并重寫(xiě)Object類中的clone()方法置森;
- 實(shí)現(xiàn)Serializable接口,通過(guò)對(duì)象的序列化和反序列化實(shí)現(xiàn)克隆掰茶,可以實(shí)現(xiàn)真正的深度克隆暇藏,代碼如下:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class MyUtil {
private MyUtil() {
throw new AssertionError();
}
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(obj);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bin);
return (T) ois.readObject();
// 說(shuō)明:調(diào)用ByteArrayInputStream或ByteArrayOutputStream對(duì)象的close方法沒(méi)有任何意義
// 這兩個(gè)基于內(nèi)存的流只要垃圾回收器清理對(duì)象就能夠釋放資源,這一點(diǎn)不同于對(duì)外部資源(如文件流)的釋放
}
}
下面是測(cè)試代碼:
import java.io.Serializable;
/**
* 人類
* @author nnngu
*
*/
class Person implements Serializable {
private static final long serialVersionUID = -9102017020286042305L;
private String name; // 姓名
private int age; // 年齡
private Car car; // 座駕
public Person(String name, int age, Car car) {
this.name = name;
this.age = age;
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
/**
* 小汽車(chē)類
* @author nnngu
*
*/
class Car implements Serializable {
private static final long serialVersionUID = -5713945027627603702L;
private String brand; // 品牌
private int maxSpeed; // 最高時(shí)速
public Car(String brand, int maxSpeed) {
this.brand = brand;
this.maxSpeed = maxSpeed;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]";
}
}
class CloneTest {
public static void main(String[] args) {
try {
Person p1 = new Person("郭靖", 33, new Car("Benz", 300));
Person p2 = MyUtil.clone(p1); // 深度克隆
p2.getCar().setBrand("BYD");
// 修改克隆的Person對(duì)象p2關(guān)聯(lián)的汽車(chē)對(duì)象的品牌屬性
// 原來(lái)的Person對(duì)象p1關(guān)聯(lián)的汽車(chē)不會(huì)受到任何影響
// 因?yàn)樵诳寺erson對(duì)象時(shí)其關(guān)聯(lián)的汽車(chē)對(duì)象也被克隆了
System.out.println(p1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:基于序列化和反序列化實(shí)現(xiàn)的克隆不僅僅是深度克隆濒蒋,更重要的是通過(guò)泛型限定盐碱,可以檢查出要克隆的對(duì)象是否支持序列化把兔,這項(xiàng)檢查是編譯器完成的,不是在運(yùn)行時(shí)拋出異常瓮顽,這種是方案明顯優(yōu)于使用Object類的clone方法克隆對(duì)象县好。讓問(wèn)題在編譯的時(shí)候暴露出來(lái)總是好過(guò)把問(wèn)題留到運(yùn)行時(shí)。
63. 深拷貝和淺拷貝區(qū)別是什么暖混?
淺拷貝只是復(fù)制了對(duì)象的引用地址缕贡,兩個(gè)對(duì)象指向同一個(gè)內(nèi)存地址,所以修改其中任意的值拣播,另一個(gè)值都會(huì)隨之變化晾咪,這就是淺拷貝(例:assign())
深拷貝是將對(duì)象及值復(fù)制過(guò)來(lái),兩個(gè)對(duì)象修改其中任意的值另一個(gè)值不會(huì)改變贮配,這就是深拷貝(例:JSON.parse()和JSON.stringify()谍倦,但是此方法無(wú)法復(fù)制函數(shù)類型)