Reputation: 29
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.
Upvotes: 0
Views: 70
Reputation: 579
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
Upvotes: 0
Reputation: 17178
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;
Upvotes: 1
Reputation: 4534
sourceImage = new int[image.length][];
for (int i=0; i<image.length; i++) {
sourceImage[i] = Arrays.copyOf(image[i],image[i].length);
}
Upvotes: 1
Reputation: 46219
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.
Upvotes: 1
Reputation: 89
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.
Upvotes: -2