陣列複製與深拷貝和淺拷貝
阿新 • • 發佈:2019-01-02
深淺拷貝針對如物件、陣列之類的複雜型別。
就陣列而言。
深拷貝
拷貝的陣列變數和原來的陣列變數是指向兩塊不同的空間,二者的操作互相不影響。
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
}
}