如果这是一个浅拷贝
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?发布于 2016-06-04 06:38:11
double[] a = new double[100];
a = b; // let b be some other double array[100]创建一个名为a的数组,其大小为100。现在,当a = b将b数组的引用复制到变量a时。
+--------------------------------------------+ <- Suppose whole
a-> | 2.5 | | | | | | | | | | | | | | array is filled
+--------------------------------------------+ with value 2.5
+--------------------------------------------+ <- Suppose whole
b-> | 7.9 | | | | | | | | | | | | | | array is filled
+--------------------------------------------+ with value 7.9在a=b之后
+--------------------------------------------+ <- 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的数组,然后调用function1(),然后再次将返回的数组引用分配给。
System.arraycopy(function1(), 0, a, 0, 100);这里的呼叫顺序是
将调用1 -> function1(),并将返回的数组引用保存在一个临时变量中。
2 ->调用System.arraycopy(temporary variable, 0, a, 0, 100)
因此,function1()只会被调用一次。
另外,请确保您使用的是System.arraycopy(args)而不是System.arrayCopy(args)
发布于 2016-06-04 06:24:59
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它在分配。将返回的值somedouble100分配给
System.arrayCopy( function1 (),0,a,0, 100 );//会调用function1 100次吗?
不,不会给function1打100次电话。以上代码主要等于
double[] tmpref = function1();
System.arrayCopy(tmparr,0,a,0,100);因为它首先计算参数,然后调用arrayCopy
https://stackoverflow.com/questions/37626972
复制相似问题