简体   繁体   中英

How to copy a multidimensional integer array into another one

So I have this block of code

public class Filter {
   int[][] sourceImage;

public Filter(int[][] image) {

    // TODO store values to sourceImage
   }
}

All I want to do here is store the values passed into image to sourceImage. Can someone please help me with how to do that? Thank You.

The easiest way would be to just do

sourceimage = image;

Note that this copies the reference to the array, so both sourceimage and the reference passed into the filter() method will point to the same array. Any changes made to the array will be visible from both references.

If sourceImage must be a distinct array, you can loop through both dimensions and copy each item:

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.
    }
}

You can do this a little quicker by making use of System.arraycopy , but explicit loops are better for learning :-)

If it's okay that the object's sourceImage is the same array as the one passed to the constructor, then you can simply assign it. Doing it this way means that any changes to one of the arrays ( image or sourceImage ) will affect them both , because they are just two references to the same array object.

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

All you have to do is use Arrays.copyOf() method so that the values of image[][] will get copied to 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);
     }
   } 

}

You have to do this because if you DO THIS

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

then if in the program you try to change the value of image then the value of sourceImage will change as they refer to the same location

You cannot pass the array. Technically only address is passed between methods. Instead you can keep the array in a class and send that class as an argument.

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

class B{
A a = new A();
public A process(A y) {
}
}

Hope this clarifies your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM