对象的克隆(clone方法)
生活随笔
收集整理的這篇文章主要介紹了
对象的克隆(clone方法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.深拷貝與淺拷貝
淺拷貝是指拷貝對象時僅僅拷貝對象本身(包括對象中的基本變量),而不拷貝對象包含的引用指向的對象。深拷貝不僅拷貝對象本身,而且拷貝對象包含的引用指向的所有對象。
2.深拷貝和淺拷貝的實現
淺拷貝的實現很簡單,直接繼承Object類的clone方法就是淺拷貝
現在說一下深拷貝,深拷貝一般的做法是把類實現Serializable接口,使得這個類具有序列化特性
然后提供深拷貝的方法,先把整個對象序列化到流里,然后再從流里反序列化出來
代碼如下
1 package test; 2 3 import java.io.*; 4 5 public class DeepCopyTest { 6 7 public static void main(String[] args) throws Exception, 8 IOException, ClassNotFoundException { 9 long t1 = System.currentTimeMillis(); 10 Professor2 p = new Professor2("wangwu", 50); 11 Student2 s1 = new Student2("zhangsan", 18, p); 12 Student2 s2 = (Student2) s1.deepClone(); 13 s2.p.name = "lisi"; 14 s2.p.age = 30; 15 System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age); // 學生1的教授不改變。 16 long t2 = System.currentTimeMillis(); 17 System.out.println(t2-t1); 18 } 19 20 } 21 22 class Professor2 implements Serializable { 23 private static final long serialVersionUID = 1L; 24 String name; 25 int age; 26 27 Professor2(String name, int age) { 28 this.name = name; 29 this.age = age; 30 } 31 } 32 33 class Student2 implements Serializable { 34 private static final long serialVersionUID = 1L; 35 String name;// 常量對象。 36 int age; 37 Professor2 p;// 學生1和學生2的引用值都是一樣的。 38 39 Student2(String name, int age, Professor2 p) { 40 this.name = name; 41 this.age = age; 42 this.p = p; 43 } 44 45 public Object deepClone() throws Exception { 46 // 將對象寫到流里 47 ByteArrayOutputStream bo = new ByteArrayOutputStream(); 48 ObjectOutputStream oo = new ObjectOutputStream(bo); 49 oo.writeObject(this); 50 // 從流里讀出來 51 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); 52 ObjectInputStream oi = new ObjectInputStream(bi); 53 return (oi.readObject()); 54 } 55 56 }?
??
轉載于:https://www.cnblogs.com/billmiao/p/9872185.html
總結
以上是生活随笔為你收集整理的对象的克隆(clone方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 11组软件工程组队项目失物招领系统——进
- 下一篇: spring @Transactiona