java数组深拷贝和浅拷贝_深拷贝和浅拷贝(数组)

1 4种数组深拷贝

package Collection;

import com.sun.xml.internal.bind.v2.TODO;

import java.util.Arrays;

public class Test4 {

public static void main(String[] args) {

int[] arr = {4, 5, 6, 7};

int[] res = copy4(arr);

arr[0] = 66;

ergodic(res);

}

//深拷贝的第一种方式

public static int[] copy1(int[] arr) {

int[] newArr = new int[arr.length];

for (int i = 0; i < arr.length; i++) {

newArr[i] = arr[i];

}

return newArr;

}

//深拷贝第二种方式

public static int[] copy2(int[] arr) {

int[] newArr = new int[arr.length];

newArr = arr.clone();

return newArr;

}

//深拷贝的第3种方式

public static int[] copy3(int[] arr) {

int[] newArr = new int[arr.length];

System.arraycopy(arr, 0, newArr, 0, arr.length);

return newArr;

}

//深拷贝的第4种方式

public static int[] copy4(int[] arr) {

int[] res = Arrays.copyOf(arr, arr.length);

return res;

}

//数组的遍历

public static void ergodic(int[] arr) {

for (int i = 0; i < arr.length; i++) {

System.out.println(arr[i]);

}

}

}

2 上面例子存在的问题

上面例子数组存储的是基本数据类型,如果把它换成引用数据类型,是否还成立呢?

答案是不成立

数组中存储的是引用数据类型,那么对该类进行拷贝,拷贝的也是指针,指针指向的会同时变化的。

3 数组中引用类型深拷贝

package Collection;

public class CloneTest implements Cloneable {

int elem;

public CloneTest(int i){

elem = i;

}

@Override

protected Object clone() throws CloneNotSupportedException {

CloneTest res = (CloneTest) super.clone();

return res;

}

public static void main(String[] args) {

CloneTest[] arr = new CloneTest[5];

for (int i = 0; i < 5; i++) {

CloneTest cloneTest = new CloneTest(i);

arr[i] = cloneTest;

}

CloneTest[] res = arr.clone();

arr[0] = new CloneTest(88);

for (int i = 0; i < res.length; i++) {

System.out.println(res[i].elem);

}

}

}

4 总结

要深拷贝一个对象a,那么

这个对象所属类必须实现Cloneable接口并重写方法,

并且

在Clone方法内部,需要把该对象a引用的的其它对象也要clone一份。

所以,

这个被应用的对象也必须实现Cloneable接口并重写方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值