Java--浅拷贝和深拷贝

Java基础–浅拷贝与深拷贝

Java中可以使用Object类中的clone()方法实现拷贝,但使用 clone() 方法来拷贝一个对象即复杂又有风险,它会抛出异常,并且还需要类型转换。Effective Java 书上讲到,最好不要去使用 clone(),可以使用拷贝构造函数或者拷贝工厂来拷贝一个对象。

1、浅拷贝

拷贝对象和原始对象引用同一个对象

package com.java.basic;

public class ShallowCloneExample {
    private int[] arr;
    public ShallowCloneExample(){
        arr = new int[10];
        for(int i=0;i<10;i++){
            arr[i] = i;
        }
    }
    public int getValue(int index) {
        return arr[index];
    }

    public void setValue(int index,int value) {
        this.arr[index] = value;
    }
    private ShallowCloneExample shallowClone(ShallowCloneExample original){
        return this;
    }

    public static void main(String[] args) {
        ShallowCloneExample s1 = new ShallowCloneExample();
        ShallowCloneExample s2 = s1.shallowClone(s1);
        System.out.println(s1.getValue(2));         //2
        System.out.println(s2.getValue(2));         //2
        s1.setValue(2,20);
        System.out.println(s1.getValue(2));         //20
        System.out.println(s2.getValue(2));         //20
    }
}

2、深拷贝

拷贝对象和原始对象引用不同的对象

package com.java.basic;

public class DeepCloneExample {
    private int[] arr;
    public DeepCloneExample(){
        arr = new int[10];
        for(int i=0;i<10;i++){
            arr[i] = i;
        }
    }
    private void setValue(int index,int value){
        this.arr[index] = value;
    }

    private int getValue(int index){
        return this.arr[index];
    }

    private DeepCloneExample(DeepCloneExample original){
        arr = new int[10];
        for(int i = 0;i<original.arr.length;i++){
            arr[i] = original.arr[i];
        }
    }

    public static void main(String[] args) {
        DeepCloneExample d1 = new DeepCloneExample();
        System.out.println(d1.getValue(2));         //2
        DeepCloneExample d2 = new DeepCloneExample(d1);
        System.out.println(d2.getValue(2));         //2
        d1.setValue(2,20);
        System.out.println(d1.getValue(2));         //20
        System.out.println(d2.getValue(2));         //2
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值