How to write a basic swap function in Java [duplicate]
I am new to java. How to write the java equivalent of the following C code.
void Swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Solution 1:
Here is one trick:
public static int getItself(int itself, int dummy)
{
return itself;
}
public static void main(String[] args)
{
int a = 10;
int b = 20;
a = getItself(b, b = a);
}
Solution 2:
Sorting two ints
The short answer is: you can't do that, java has no pointers.
But here's something similar that you can do:
public void swap(AtomicInteger a, AtomicInteger b){
// look mom, no tmp variables needed
a.set(b.getAndSet(a.get()));
}
You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.
BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int)
:
Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Sorting an int[] array
apparently the real objective is to sort an array of ints.
That's a one-liner with Arrays.sort(int[])
:
int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);
To check the output:
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]
And here is a simple helper function to swap two positions in an array of ints:
public static void swap(final int[] arr, final int pos1, final int pos2){
final int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
Solution 3:
Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.
class Swap
{
public static void main (String[] args)
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
System.out.println("New values of x and y are "+ x + ", " + y);
}
}
Output:
New values of x and y are 10, 5