public static void reverseArray(int[] arr) {
int[] reversed = new int[arr.length];
for (int i = arr.length - 1; i > -1; --i) {
reversed[arr.length - i - 1] = arr[i];
}
arr = reversed;
}
Here I have a reverse array method. If I call
int[] v = new int[] {1, 2, 3, 4};
reverseArray(v);
//print v
I would get "1 2 3 4"
But if I changed the reverseArray function to
public static void reverseArray(int[] arr) {
int[] reversed = new int[arr.length];
for (int i = arr.length - 1; i > -1; --i) {
reversed[arr.length - i - 1] = arr[i];
}
for (int i = 0; i < arr.length; ++i) {
arr[i] = reversed[i];
}
}
It will work as intended and print out "4 3 2 1" Why didn't the "arr = reversed;" work? They are both pointers so if I assign one to the other it should point to the same objects like with the 2D arrays. If I do
int[][] mat = //some assignment
public void reverseMatrix() {
reverseAllRows();
int[][] c = new int[mat.length][mat[0].length];
for (int i = 0; i < mat.length; ++i) {
c[mat.length - 1 - i] = mat[i];
}
mat = c; //This works for some reason
}
It works without having me to copy each one of the elements. Why is that and how do I know when it is the case to use equals and when not to?