簡體   English   中英

如何將多維整數數組復制到另一個數組

[英]How to copy a multidimensional integer array into another one

所以我有這段代碼

public class Filter {
   int[][] sourceImage;

public Filter(int[][] image) {

    // TODO store values to sourceImage
   }
}

我在這里要做的就是將傳入圖像的值存儲到sourceImage中。 有人可以幫我怎么做嗎? 謝謝。

最簡單的方法是

sourceimage = image;

請注意,這sourceimage引用復制到數組,因此sourceimage和傳遞給filter()方法的引用都將指向同一數組。 從兩個引用中都可以看到對該數組所做的任何更改。

如果sourceImage必須是一個不同的數組,則可以遍歷兩個維度並復制每個項目:

sourceImage = new int[image.length][]; // Initialize the first dimension.
for (int i=0; i<sourceImage.length; i++) {
    sourceImage[i] = new int[image[i].length]; // Initialize the 2nd dimension.
    for (int j=0; j<sourceImage[i].length; j++) {
        sourceImage[i][j] = image[i][j]; // Copy each value.
    }
}

您可以通過使用System.arraycopy更快地完成此操作,但是顯式循環更適合於學習:-)

如果對象的sourceImage 傳遞給構造函數的數組相同 ,則可以簡單地分配它。 這樣做意味着對數組之一( imagesourceImage )的任何更改都會影響它們兩個 ,因為它們只是對同一數組對象的兩個引用。

sourceImage = image;
sourceImage = new int[image.length][];
for (int i=0; i<image.length; i++) {
    sourceImage[i] = Arrays.copyOf(image[i],image[i].length);
}

您所要做的就是使用Arrays.copyOf()方法,以便將image [] []的值復制到sourceImage [] []

public class Filter {
   int[][] sourceImage;

public Filter(int[][] image) {

        sourceImage = new int[image.length][];

    for (int i = 0; i < image.length; ++i) {
         sourceImage[i] = Arrays.copyOf(image[i], image[i].length);
     }
   } 

}

您必須這樣做,因為如果這樣做

sourceImage=image;//(WHICH SHOULD NEVER BE DONE UNLESS YOU ACTUALLY WANT BOTH TO REFER TO THE SAME LOCATION)

然后,如果您在程序中嘗試更改image的值,則sourceImage的值將更改,因為它們引用相同的位置

您不能傳遞數組。 從技術上講,僅地址在方法之間傳遞。 相反,您可以將數組保留在一個類中,然后將該類作為參數發送。

A級{
int arr [] = {1,2,3,4,5};
}

B級{
A a = new A();
公共A進程(y){
}
}

希望這可以澄清您的問題。

暫無
暫無

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

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