使用System.arrayCopy复制基本类型的数组,是浅还是深?

时间:2017-02-27 14:37:40

标签: java arrays deep-copy primitive-types shallow-copy

我理解Object[]如何创建传递给它的int[]数组的浅表副本。

但我不明白它如何对基本类型的数组起作用,例如byte[]SET DATEFORMAT dmy; DECLARE @Dummy TABLE(ID INT,[user] VARCHAR(100),[from] DATE,[to] DATE,loan INT); INSERT INTO @Dummy VALUES (1,'BB','01/01/2016','01/05/2016',50) ,(2,'AD','01/01/2016','01/03/2016',25) ,(3,'AD','01/03/2016','17/05/2016',30); DECLARE @FirstDay DATE='01/01/2016'; WITH SomeNumbers AS --replace this with a values/tally/numbers/date table ( SELECT * FROM(VALUES(0),(1),(2),(3)) AS t(Nr) ) SELECT DISTINCT x.FirstOfMonth ,FittingData.* FROM SomeNumbers CROSS APPLY(SELECT DATEADD(MONTH,SomeNumbers.Nr,@FirstDay) AS FirstOfMonth) AS x CROSS APPLY(SELECT * FROM @Dummy AS d WHERE x.FirstOfMonth>=d.[from] AND x.FirstOfMonth<d.[to]) AS FittingData WHERE ID IS NOT NULL ORDER BY ID,[from] 。没有复制参考。在这种情况下,浅层或深层副本应该没有任何区别。

2 个答案:

答案 0 :(得分:2)

正如你所说:

  

没有复制参考。在这种情况下,浅层或深层副本应该没有任何区别。

对于基元,System.arrayCopy只复制数组元素的值。

答案 1 :(得分:0)

原始类型数组上的System.arrayCopy()会产生深层复制。

从您的评论中: &#34;在这种情况下,浅层或深层副本应该没有任何区别&#34;

有区别。如果目标阵列在更改后是浅层副本,则对目标阵列所做的更改应该影响源阵列,反之亦然。但这不是这种情况。

让我举一个例子:

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]

如果您看到结果,如果是浅色副本,&#34;更改为arr1&#34;应该结果

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

但事实并非如此,因为System.arrayCopy会导致原始类型的深层复制。我希望这能回答你的问题。