I now know that to interchange array values you have to do something like this
String t = a[1];
a[1] = a[2];
a[2] = t;
My question is why is it not possible to just directly do
a[1] = a[2];
a[2] = a[1];
or
a[1] = 2;
a[2] = 1;
I now know that to interchange array values you have to do something like this
String t = a[1];
a[1] = a[2];
a[2] = t;
My question is why is it not possible to just directly do
a[1] = a[2];
a[2] = a[1];
or
a[1] = 2;
a[2] = 1;
From Here
If you're swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it's also a one liner.
public static void swap(int[] arr, int i, int j) {
arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}
What I've seen from some primitive benchmarks is that the performance difference is basically negligible as well.
This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.
Program statements are executed sequentially.
Therefore, as you replace one array value(x[0]
) with the other (x[1]
), then that statement occurs before any other.
To avoid this, you must store x[0]
into a variable as the value at x[0]
will be replaced before x[1]
could be assigned, due to computer's sequential nature