Efficient swapping of elements of an array in Java
Solution 1:
Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final
).
Solution 2:
This should make it seamless:
public static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
public static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
private void test() {
String [] a = {"Hello", "Goodbye"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
Solution 3:
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.