I am trying to flip each col in this array to invert the image. However, when I run my code, I get a mirror image of the second half of the image, for some ridiculous reason, that I cannot figure out. Can someone please tell me why this only works half-way?
public void invert() { int[][] tempArray= someArray; for(int row = 0; row < someArray.length; ++row) { int x = someArray[row].length - 1; for(int col = 0; col < someArray[i].length; ++col, --x) { tempArray[row][col] = someArray[row][x]; } } someArray = tempArray; }
someArray is an int[][] array defined elsewhere in my class of size 328×500 int x is a counter variable to decrement through the columns backwards
Advertisement
Answer
The problem is because you are manipulating the same array.
Remember java arrays
are reference types. So your tempArray
and someArray
is referring to the same array.
Now, let’s say row 1 of your array is {1,2,3}
and your output should be {3,2,1}
.
But since it’s the same array, during the first iteration, the array will become {3,2,3}
. And in the third iteration you are reading the same array and trying to replace 3
in col=2
with the 3
in col=0
. So your result is 3,2,3
.
You should instead create a new array.
replace:
int[][] tempArray= someArray;
with
int[][] tempArray = new int[someArray.length][someArray[0].length]; // If you have variable length column, you may want to intialize it inside the loop.