簡體   English   中英

Java淺拷貝數組

[英]Java shallow copy array

如果這是淺表副本

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?
double[] a = new double[100];
a = b; // let b be some other double array[100]

創建一個名為a的double數組,其大小為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()並再次將返回的數組引用分配給a。

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)

    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]分配


System.arrayCopy(function1(),0,a,0,100); //此函數會調用100次100次嗎?

不,它不會調用function1 100次。 上面的代碼大部分等於

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

因為它首先計算參數,然后調用arrayCopy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM