If you've ever used C or C++ and know about how pointers work, then what made this whole scenario tick for me is the following statement:
In Java, everything is passed by value.
In case of Objects, the reference (pointer) is passed by value.
So basically the swap function of
public void swap(int[] a, int[] b)
{
etc.
}
Will just get the pointer to the a
int[] array, and the pointer to the b
int[] array.
You're just swapping two pointers. You cannot modify the content of pointers like that.
Basically the C equivalent is
void swap(int* a, int* b)
{
int* temp = a;
a = b;
b = temp;
}
int main(void)
{
int a[] = {5,6,7,8};
int b[] = {1,2,3,4};
swap(a,b);
}
While even in C, this would only work like so:
void swap(int** a, int** b)
{
int* temp = (*a);
(*a) = (*b);
(*b) = temp;
}
int main(void)
{
int a[] = {5,6,7,8};
int b[] = {1,2,3,4};
swap(&a, &b);
}
Of course, you can't send the reference of a reference in Java. Pointers in this sense don't exist in Java.
Therefore, in order to actually modify the object in another function, you would need a "Holder" object to which the reference is copied, but the reference inside it to the object you want to modify IS actually the actual reference of the object, if that made sense.
And thus, the following would work:
public class ArrayHolder
{
public int[] array;
public ArrayHolder(int[] array)
{
this.array = array;
}
}
public void swap(ArrayHolder a, ArrayHolder b)
{
int[] temp = a.array;
a.array = b.array;
b.array = temp;
}
public static void main(String[] args)
{
ArrayHolder aaa = new ArrayHolder(new int[] {5,6,7,8});
ArrayHolder bbb = new ArrayHolder(new int[] {1,2,3,4});
swap(aaa,bbb);
}