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?
Use Collections. swap() to Swap Two Elements of an Array in Java. The swap() method of the Collections class swaps elements at the specified position in the specified list.
The technique of swapping two variables in coding refers to the exchange of the variables' values. In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array.
To swap elements of two arrays you have to swap each pair of elemenets separatly. And you have to supply the number of elements in the arrays. Otherwise the arrays need to have a sentinel value. Here is a demonstrative program that shows how the function swap can be defined.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With