淺拷貝:
在堆內存中不會分配新的空間,而是增加一個引用變量和之前的引用指向相同的堆空間。
int[] a = {1,2,3,4,5};
int[]b = a;
public class Test { public static void main(String[] args) { //數組的淺拷貝,a,b兩個引用指向同一個數組 int[] a = {1,2,3,4,5}; int[] b = a; for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } System.out.println(); } }
深拷貝:
在堆內存中分配新空間,將之前的數組堆內存中的內容拷貝到新的空間中。
int[] a = {1,2,3,4,5};
int[] b = new int[5];
System.arraycopy(a, 0, b, 0, 5);
public class Test { public static void main(String[] args) { //數組的深拷貝,a,b兩個引用指向同一個數組 int[] a = {1,2,3,4,5}; int[] b = new int[5]; /** * System.arraycopy(src, srcPos, dest, destPos, length); * src:源數組 * srcPos:源數組中拷貝的起始位置 * dest:目標數組 * destPos:目標數組中開始存放的位置 * length:拷貝的長度 */ System.arraycopy(a, 0, b, 0, a.length); for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } System.out.println(); } }