Efficient swapping of elements of an array in Java

algorithm, java, swap

Solution

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`).

Problem

I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this: ``` String temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; ``` Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?

Original source