深浅拷贝针对如对象、数组之类的复杂类型。
就数组而言。
深拷贝
拷贝的数组变量和原来的数组变量是指向两块不同的空间,二者的操作互相不影响。
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;
数组复制的方法
- 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
}
}
- 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
}
}
- 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]);
}
}
- 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
}
}
- 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
}
}