Java浅拷贝数组

时间:2016-06-04 06:08:18

标签: java arrays

如果这是浅拷贝

double[] a = new double[100];
a = b; // let b be some other double array[100]

我知道更好的方法是使用for循环或使用

System.arrayCopy(b,0,a,0,100);

然而,这会发生什么?

public double[] function1(){
    returns somedouble[100];
}

double[] a = new double[100];
a = function1(); // i believe this will also be a shallow copy

System.arrayCopy(function1(),0,a,0,100); // will this call function1 100 times?

2 个答案:

答案 0 :(得分:2)

double[] a = new double[100];
a = b; // let b be some other double array[100]

创建一个名为a的数组为a = b的数组,大小为100.现在, +--------------------------------------------+ <- Suppose whole a-> | 2.5 | | | | | | | | | | | | | | array is filled +--------------------------------------------+ with value 2.5 +--------------------------------------------+ <- Suppose whole b-> | 7.9 | | | | | | | | | | | | | | array is filled +--------------------------------------------+ with value 7.9 将b数组的引用复制到变量a。

     +--------------------------------------------+  <- Suppose whole
     | 2.5 |  |  |  |  |  |  |  |  |  |  |  |  |  |  array is filled 
     +--------------------------------------------+  with value 2.5

a->  +--------------------------------------------+  <- Suppose whole
b->  | 7.9 |  |  |  |  |  |  |  |  |  |  |  |  |  |  array is filled 
     +--------------------------------------------+  with value 7.9
a = b后

public double[] function1(){
    return somedouble[100];
}

double[] a = new double[100];
a = function1();

所以现在a和b指向同一个数组。

function1()

现在同样的事情发生在这里。您创建一个名为a的数组,然后调用System.arraycopy(function1(), 0, a, 0, 100); 并再次将返回的数组引用分配给。

System.arraycopy(temporary variable, 0, a, 0, 100)

这里的呼叫顺序是

1 - &gt;将调用function1()并将返回的数组引用保存在临时变量中。

2 - &gt;致电function1()

所以System.arraycopy(args)只会被调用一次。

作为旁注,请务必使用System.arrayCopy(args)代替ans.push_back((char)('0' + rem))

答案 1 :(得分:0)

    double[] a = new double[100];
    a = b; // let b be some other double array[100]

首先,它是分配,而不是复制。

    double[] a = new double[100];
    a = function1(); // i believe this will also be a shallow copy

它正在分配。您将返回值 somedouble [100] 分配给 a

  

System.arrayCopy(功能1(),0,A,0100); //这会调用function1 100次吗?

不,它不会100次调用function1。上面的代码大多等于

    double[] tmpref = function1();
    System.arrayCopy(tmparr,0,a,0,100);

因为它首先评估参数,所以它调用 arrayCopy