java拷貝陣列(深拷貝)
阿新 • • 發佈:2019-02-18
假設陣列a,b。要把陣列a中的元素拷貝到b中,如果直接b = a的話。就會使b指向a的儲存區域,對b的修改也會引發a中元素的修改(淺拷貝)。
public class ShallowCopy {
public static void main(String[] args) {
int[] a = {1, 2};
int[] b = a;
b[1] = 7;
System.out.println("a[1] = " + a[1]);
}
}
此時控制檯輸出a[1] = 7。
如果我們希望b拷貝a而不和a指向同一塊堆記憶體空間(深拷貝),我們大致有三種方法可以選擇:
1、for /while迴圈,一個一個複製,這個就不多說了;
2、使用System類中的靜態方法arraycopy/Arrays類中的copyOf:
public class CopyArrayByarraycopy { public static void main(String[] args) { int[] a = {1, 2, 3, 4}; int[] b = new int[4]; System.arraycopy(a, 0, b, 0, a.length); b[3] = 7; System.out.println("Array a:"); for (int i : a) System.out.print(i + " "); System.out.println(); System.out.println("Array b:"); for (int j : b) System.out.print(j + " "); } }
//匯入Arrays類 import java.util.Arrays; public class CopyArrayByCopyof { public static void main(String[] args) { int[] a = new int[10]; //copyOf方法 int[] copy = Arrays.copyOf(a, a.length * 2); //第一個引數為要拷貝的陣列名,第二個為拷貝陣列的大小(不限定大小,可用於擴大陣列,如可以是a.length * 2) System.out.println(a[1] + " " + copy[2] ); } }
兩者關係如下,可以看到copyOf呼叫arraycopy:
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
3、陣列物件的clone方法:
public class CopyArrayByClone {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4};
int[] b = a.clone();
a[0] = 91;
b[1] = 7;
System.out.println("Array a:");
for (int i : a)
System.out.print(i + " ");
System.out.println();
System.out.println("Array b:");
for (int j : b)
System.out.print(j + " ");
}
}