how do I make my swap function in java if there is no method by which we can pass by reference? Could somebody give me a code?
swap(int a, int b) { int temp = a; a = b; b = temp; }
But the changes wont be reflected back since java passes parameters by value.
The swap() method of java. util. Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.
In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.
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.
I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:
int swap(int a, int b) { // usage: y = swap(x, x=y); return a; } y = swap(x, x=y);
It relies on the fact that x
will pass into swap
before y
is assigned to x
, then x
is returned and assigned to y
.
You can make it generic and swap any number of objects of the same type:
<T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z); return args[0]; } c = swap(a, a=b, b=c)
You can't create a method swap, so that after calling swap(x,y)
the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.
You can however write a method that swaps two items in an array or list if that's what you want.
¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.
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