Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient swapping of elements of an array in Java

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?

like image 600
Robin Avatar asked Dec 07 '12 15:12

Robin


People also ask

How do you swap elements in an array Java?

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.

Can you swap elements in arrays?

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.

How do you swap elements between two arrays?

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.


1 Answers

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

like image 107
T.J. Crowder Avatar answered Oct 06 '22 03:10

T.J. Crowder