java的深拷贝和浅拷贝

xiaoxiao2021-02-28  86

1.浅拷贝与深拷贝概念

深拷贝的本质就是把引用数据类型赋值改成基本数据类型赋值

浅拷贝就是引用数据类型的赋值引用赋值必捆绑

第一个类

package cn.hncu.kaobei;

public class MyDate{   private int year;   private int month;   private int day;      public MyDate(int year,int month,int day){    this.year=year;    this.month=month;    this.day=day;   }   public MyDate(){    this(1970,1,1);   }   public MyDate( MyDate d){    this(d.year,d.month,d.day);   }   public void setYear(int year){    this.year = year;   }   public String toString(){    return year+"年"+month+"月"+day+"日";   }

}

第二个类

package cn.hncu.kaobei; public class Person{   private String name;   private MyDate birth;      public Person(String name,MyDate birth){    this.name = name;    //this.birth = birth;//引用赋值必捆绑----出现浅拷贝       //深拷贝的本质就是把"引用赋值" 变成 "基本数据类型或String类型赋值"    this.birth = new MyDate(birth);   }   public Person(){    this("NoName",null);   }   public Person( Person p ){    this(p.name, p.birth);   }      public void setName(String name){    this.name = name;   }   public MyDate getBirth(){    return birth;   }      public String toString(){    return name+","+birth.toString();   }    }

第三个类

package cn.hncu.kaobei; public class Client{   public static void main(String args[]){     MyDate d = new MyDate(1995,4,22);      Person p = new Person("Jack",d);      System.out.println("p::: "+ p.toString() );//Jack,1995年4月22日      System.out.println("--------------");            /*      Person p2 = p;//引用赋值必捆绑--浅拷贝      p.setName("Tom");      p.getBirth().setYear(2000);      System.out.println("p::: "+ p.toString() );//Tom,2000年4月22日      System.out.println("p2::: "+ p2.toString() );//Tom,2000年4月22日      */      

     Person p3 = new Person(p);//深拷贝,不捆绑      p.setName("Tom");      p.getBirth().setYear(2000);      System.out.println("p::: "+ p.toString() );//Tom,2000年4月22日      System.out.println("p3::: "+ p3.toString() );//Jack,1995年4月22日         } }

转载请注明原文地址: https://www.6miu.com/read-70164.html

最新回复(0)