数组和List浅拷贝和深拷贝
数组拷贝
1. clone方法
public class ArrayCopyTest {
public static void main(String[] args) {
int[] a1 = {-1, 2, 3};
//浅拷贝
int[] a2 = a1;
a2[0] = 2;
//深拷贝
int[] a3 = a1.clone();
a3[0] = 3;
System.out.println("a1" + Arrays.toString(a1));
System.out.println("a2" + Arrays.toString(a2));
System.out.println("a2" + Arrays.toString(a3));
}
}
运行结果:
可以看到clone方法就是深拷贝。
2. System.arraycopy
System.arraycopy方法是一个本地的方法,源码里定义如下:
public static native void arraycopy(Object src, int srcPos, Object dest, int desPos, int length)
也就是:(原数组, 原数组的开始位置, 目标数组, 目标数组的开始位置, 拷贝个数)
int[] a4 = new int[10];
System.arraycopy(a1, 1, a4, 3, 2);
System.out.println("a4" + Arrays.toString(a4));
注意length不能越界,否则会报异常。
3. Arrays.copyOf
其实Arrays.copyOf也是调用的System.arraycopy方法,因此也是深拷贝
int[] a5 = Arrays.copyOf(a1, 2);
System.out.println("a5" + Arrays.toString(a5));
List深拷贝
首先来看一段代码
public class CopyTest {
public static void main(String[] args) {
List<Integer> a = new LinkedList<>();
a.add(1);
a.add(2);
List<Integer> b = new LinkedList<>(a);
b.set(0, 3);
List<Integer> c = new LinkedList<>();
c.addAll(a);
c.set(0, 4);
List<Integer> d = a;
d.set(0, 5);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
代码输出:
可以看到
使用“==”符号的是浅拷贝
addAll和直接通过构造函数的拷贝都是深拷贝