数组复制与深拷贝和浅拷贝

深浅拷贝针对如对象、数组之类的复杂类型。
就数组而言。

深拷贝

拷贝的数组变量和原来的数组变量是指向两块不同的空间,二者的操作互相不影响。

int[] a = new int[]{1,2,3,4,5};
int[] b = new int[5];
for(int i = 0;i < 5;i++){
    b[i] = a[i];
}
浅拷贝

拷贝的数组变量和原来的数组变量是指向同一块空间,因此对二者任意一个变量操作,都影响了另一个数组变量。

int[] a = new int[]{1,2,3,4,5};
int[] b = a;
数组复制的方法
  1. for循环 <因为要new一个数组在循环复制,深拷贝>
public class test {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3,4,5};
        int[] b = new int[5];
        for(int i = 0;i < 5;i++){
            b[i] = a[i];
        }
        b[2] = 100;
        System.out.println(a[2]); //3
        System.out.println(b[2]); //100
    }
}
  1. System.arraycopy() <,需要对拷贝的数组初始化,所有和被拷贝的数组肯定不是指向同一块内存,深拷贝>
public class test {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3};
        int[] b = new int[3];
        System.arraycopy(a,0,b,0,3);
        b[2] = 100;
        System.out.println(a[2]); //3
        System.out.println(b[2]); //100
    }
}
  1. Arrays.copyOf() <深拷贝>
public class test {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3};
        int[] b;
        b = Arrays.copyOf(a,3);
        b[2] = 100;
        System.out.println(a[2]);
        System.out.println(b[2]);
    }
}
  1. Object.clone()<深拷贝>(对于对象来说是深拷贝,java中吧数组看成对象)
public class test {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3};
        int[] b;
        b = a.clone();
        b[2] = 100;
        System.out.println(a[2]); //3
        System.out.println(b[2]); //100
    }
}
  1. Arrays.copyOfRange()
public class test {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3};
        int[] b;
        b = Arrays.copyOfRange(a,0,3);
        b[12] = 100;
        System.out.println(a[2]); //3
        System.out.println(b[2]); //100
    }
}
参考

Java数组拷贝的四种方法
深拷贝和浅拷贝的实现

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值