使用系统的原始类型的复制阵列.ararayCopy,它是浅或深的



我了解System.arrayCopy()如何创建传递给它的Object[]数组的浅副本。

,但我不明白它如何在原始类型的数组(例如int[]byte[])上工作。没有参考可以复制。在这种情况下,浅或深拷贝不应有任何区别。

如您所述:

没有参考可以复制。在这种情况下,浅或深拷贝不应有任何区别。

对于原始素,System.arrayCopy仅复制数组元素的值。

system.ArrayCopy()在原始类型的阵列上结果深拷贝。

从您的评论中:"在这种情况下,浅或深拷贝不应有任何区别"

有区别。如果目标数组是更改后的浅副本,则您对目标数组的更改应影响源数组,反之亦然。但这里不是这样。

让我在这里举一个例子:

public class ArrayCopy {
public static void main(String args[]) {
    int arr1[] = {0, 1, 2, 3, 4, 5};
    int arr2[] = {10, 11, 12, 13, 14, 15};
    System.out.println("Before change");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
    System.arraycopy(arr1, 0, arr2, 0, 3);
    System.out.println("After change for arr2");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
    int arr3[] = {20, 30};
    System.arraycopy(arr3, 0, arr1, 0, 2);
    System.out.println("After change for arr1");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
}}
     Result:
 Before change
 arr1 [0, 1, 2, 3, 4, 5]
 arr2 [10, 11, 12, 13, 14, 15]
 After change for arr2
 arr1 [0, 1, 2, 3, 4, 5]
 arr2 [0, 1, 2, 13, 14, 15]
 After change for arr1
 arr1 [20, 30, 2, 3, 4, 5]
 arr2 [0, 1, 2, 13, 14, 15]

如果您看到结果,如果是浅副本,则" ARR1更改后"应结果

                  arr1 [20, 30, 2, 3, 4, 5]
                  arr2 [20, 30, 2, 13, 14, 15]

但事实并非如此,因为系统。arraycopy导致原始类型的深层复制。我希望这可以回答您的问题。

最新更新