Java中clone中浅拷贝、深拷贝(对象)

前面的博客已经提到了一维数组和二维数组的拷贝的判断。

Java中常用的是对对象的拷贝。

对象的拷贝:

1、可以直接

2、clone()

Peolple类:

package Lianxi;

public class Peolple implements Cloneable{
    private String name;
    private  int age;
    private  int  height;
   public  Student  student;
    public  Peolple(String name,int age){
        this.name=name;
        this.age=age;
        student=new Student();
    }
    public void eat(){

    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void drink(){

    }
    @Override
    protected Object clone() throws CloneNotSupportedException {

      Peolple  p=(Peolple)super.clone();     //只能对基本数据类型和String类型进行深拷贝  
                                                              //引用数据类型不行
      p.student=(Student)student.clone();  //调用Student中重写的对Student中的内容进行拷贝
      
      return p;


    }
}

Student类:

package Lianxi;

public class Student  implements Cloneable{
    public  int age=1;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Test

package Lianxi;

import zuoye4.People;

public class Test {

     public static  void main(String []args){

         Peolple p1=new Peolple("wo",10);
         Peolple p2=null;

         try{
            p2=(Peolple)p1.clone();
         }
         catch(Exception e){

         }
         System.out.println(p1.getAge()+p1.getName()+p1.student.age);
         System.out.println(p2.getAge()+p2.getName()+p2.student.age);
         p1.student.age=50;
         System.out.println(p1.student.age);
         System.out.println(p2.student.age);

    }
}

输出结果:

10wo1
10wo1
50
1

该过程用clone()实现深拷贝。

注意:对引用数据的深拷贝,要重写clone()方法。

         

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值