久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java怎么實(shí)現(xiàn)對象克隆

161次閱讀
沒有評論

共計(jì) 1761 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。

在 Java 中,可以通過兩種方式來實(shí)現(xiàn)對象克隆:淺拷貝和深拷貝。

  1. 淺拷貝:使用 Object 類的 clone() 方法進(jìn)行對象的淺拷貝。淺拷貝會創(chuàng)建一個(gè)新的對象,將原始對象的非靜態(tài)字段的值復(fù)制到新對象中,對于引用類型的字段,復(fù)制的是引用而不是對象本身。如果原始對象中的字段是可變的,修改新對象中的字段會影響原始對象,反之亦然。

例如:

public class MyClass implements Cloneable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
@Override
public Object clone() throws CloneNotSupportedException {return super.clone();
}
public static void main(String[] args) {MyClass obj1 = new MyClass(10, "Hello");
try {MyClass obj2 = (MyClass) obj1.clone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // true
} catch (CloneNotSupportedException e) {e.printStackTrace();
}
}
}
  1. 深拷貝:通過實(shí)現(xiàn) Serializable 接口以及使用序列化和反序列化的方式實(shí)現(xiàn)對象的深拷貝。深拷貝會創(chuàng)建一個(gè)新的對象,將原始對象及其引用的對象都復(fù)制到新對象中,新對象與原始對象是完全獨(dú)立的。

例如:

import java.io.*;
public class MyClass implements Serializable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
public MyClass deepClone() throws IOException, ClassNotFoundException {ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MyClass) ois.readObject();}
public static void main(String[] args) {MyClass obj1 = new MyClass(10, "Hello");
try {MyClass obj2 = obj1.deepClone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // false
} catch (IOException | ClassNotFoundException e) {e.printStackTrace();
}
}
}

需要注意的是,要實(shí)現(xiàn)深拷貝,對象及其引用的對象都需要實(shí)現(xiàn) Serializable 接口。

丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-21發(fā)表,共計(jì)1761字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 富顺县| 双桥区| 长葛市| 大埔县| 阜宁县| 会东县| 石屏县| 水富县| 海宁市| 望谟县| 郸城县| 西和县| 黄梅县| 无锡市| 泰和县| 滨海县| 青浦区| 喀喇| 霍州市| 黔西县| 松阳县| 平远县| 庐江县| 巩义市| 易门县| 郸城县| 贵南县| 伊金霍洛旗| 河东区| 克东县| 恩施市| 浪卡子县| 修水县| 寿宁县| 图木舒克市| 台江县| 北票市| 息烽县| 德昌县| 商水县| 大安市|