对象赋值

Java中的对象克隆(复制)

一个简单的变量复制

int old = 20;
int new = old;
对于基本数据类型的复制都是等同的——boolean,char,byte,short,float,double.long

复杂变量——对象

/**
* Created by CaiTieZhu on 2018/9/23 18:12
*/
class People{
    private int money;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

}
public class PeopleTester{
    public static void main(String[] args) {
        People rich = new People();
        rich.setMoney(500);
        
        People poor = rich;
        
        System.out.println("Rich have : " + rich.getMoney());
        System.out.println("Poor have : " + poor.getMoney());
    }
}

运行结果:

Rich have : 500
Poor have : 500

按照一般的思维的话,这个结果是在意料之中的,因为我穷人去拷贝了富人这个对象,所以我的钱应该跟他是一样多的。

此时,富人的钱花出去了一百。

People poor = rich;

rich.setMoney(500-100);

System.out.println("Rich have : " + rich.getMoney());
System.out.println("Poor have : " + poor.getMoney());

运行结果:

Rich have : 400
Poor have : 400

穷人并没有花钱,但是穷人的钱也变成了400。

因为复杂对象的拷贝是引用传递,而基本数据类型的拷贝是值传递。

对象拷贝的是被拷贝对象的地址,比如rich和poor两个对象,指向的都是同一块内存地址,而对象的成员变量都存放在这一块内存中,所以具体的来说,改变的并不是富人的变量,而是这一块堆内存的变量,rich和poor只是拥有一个指向该内存的指针。

如何复制一个对象

Object中有一个clone()方法

/** clone()方法 **/
protected native Object clone() throws CloneNotSupportedException;

该方法的上有这样子一部分的注释:

    x.clone() != x
        will be true
    x.clone().getClass() == x.getClass()
        will be true, but these are not absolute requirements.
    x.clone().equals(x)
        will be true, this is not an absolute requirement.

clone()出来的对象跟原来的对象时同时独立存在的。

举个例子:

/**
* Created by CaiTieZhu on 2018/9/23 18:12
*/
class People implements Cloneable{
    private int money;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class PeopleTester{
    public static void main(String[] args) throws CloneNotSupportedException {
        People rich = new People();
        rich.setMoney(500);

        People poor = (People) rich.clone();

        rich.setMoney(500-100);


        System.out.println("Rich have : " + rich.getMoney());
        System.out.println("Poor have : " + poor.getMoney());
    }
}

运行结果:

Rich have : 400
Poor have : 500

使用clone()的时候,需要实现Cloneable接口,否则会抛出CloneNotSupportedException异常。

Java中不同的两种拷贝方式:

浅拷贝(ShallowClone)和深拷贝(DeepClone)

[区别]
    浅拷贝和深拷贝的主要区别在于是否支持引用类型的成员变量的复制。
    浅拷贝:
        对于基本数据类型采用值传递,对于复杂数据类型采用引用传递方式。
    深拷贝:
        对基本数据类型采用值传递方式,对于复杂数据类型采用开辟新的内存空间,指针指向新地址的方式。

浅拷贝的两种方式:

[通过构造器来创建新的实例]
    /** 举个例子 **/
    /**
    * Created by CaiTieZhu on 2018/9/26 15:44
    */
    class People{
        private int money;

        public  People(){
        }

        public People(People people){
            this.money = people.getMoney();
        }

        public int getMoney() {
            return money;
        }

        public void setMoney(int money) {
            this.money = money;
        }
    }
    public class PeopleTester {
        public static void main(String[] args) {
            People rich = new People();
            /** 有钱人有500块钱 **/
            rich.setMoney(500);
            /** 通过构造器浅拷贝对象 **/
            People poor = new People(rich);
            /** 有钱人花掉了100块钱 **/
            rich.setMoney(500-100);

            System.out.println("Rich have : " + rich.getMoney());
            System.out.println("Poor have : " + poor.getMoney());
        }
    }

    运行结果:
    
    Rich have : 400
    Poor have : 500

[通过clone()方法实现]
    上面有样例代码。

深拷贝的两种方式:

[通过对每个复杂成员变量重写clone()方法来实现]

/**
* Created by CaiTieZhu on 2018/9/23 18:12
*/
class People implements Cloneable{
    private Address address;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        /** 获取拷贝对象 **/
        Object object = null;
        try {
            object = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        /** 转换成People类的实例 **/
        People people = (People) object;
        /** 克隆Address **/
        people.address = (Address) people.getAddress().clone();
        return object;
    }
}
class Address implements Cloneable{

    private String addressInfo;

    public String getAddressInfo() {
        return addressInfo;
    }

    public void setAddressInfo(String addressInfo) {
        this.addressInfo = addressInfo;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class PeopleTester{
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address();
        address.setAddressInfo("富人区");

        People rich = new People();
        rich.setAddress(address);

        People poor = (People) rich.clone();

        poor.getAddress().setAddressInfo("穷人区");

        System.out.println("Rich have : " + rich.getAddress().getAddressInfo());
        System.out.println("Poor have : " + poor.getAddress().getAddressInfo());
    }
}


运行结果:

Rich have : 富人区
Poor have : 穷人区

但是这种方法存在缺点,就是当一个类的成员变量很多或者成员变量层次很深的时候,采用clone()方法会显得很繁琐。

[通过序列化克隆对象]
    import java.io.*;
    /**
    * Created by CaiTieZhu on 2018/9/23 18:12
    */
    class People implements Serializable {
        private Address address;

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

    }
    class Address implements Serializable{

        private String addressInfo;

        public String getAddressInfo() {
            return addressInfo;
        }

        public void setAddressInfo(String addressInfo) {
            this.addressInfo = addressInfo;
        }

    }
    public class PeopleTester{
        public static void main(String[] args) throws ClassNotFoundException, IOException {
            Address address = new Address();
            address.setAddressInfo("富人区");

            People rich = new People();
            rich.setAddress(address);

            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(rich);
            oos.flush();
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            People poor = (People) ois.readObject();

            poor.getAddress().setAddressInfo("穷人区");

            System.out.println("Rich have : " + rich.getAddress().getAddressInfo());
            System.out.println("Poor have : " + poor.getAddress().getAddressInfo());
        }
    }

运行结果:

Rich have : 富人区
Poor have : 穷人区

当某个属性被transient关键字修饰的时候,该属性不支持序列化。

总结就是:

 浅拷贝:假如A要复制B(具有引用类型的成员变量还有普通变量),A先创建出空间,引用类型的成员变量是通过引用赋值,他们指向的是同一个内存地址,普通变量是通过赋值。可以通过重写clone实现,直接super就可以了。

深拷贝:除了普通变量是赋值传递以外,引用类型的成员变量也是赋值传递,有两种方法:重写clone,引用类型中的变量要一个个实现传值,第二种方法就是序列化传递,如果当某个属性被transient关键字修饰的时候,该属性不支持序列化。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值