Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method to swap primitives

Tags:

java

swap

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.

like image 449
higherDefender Avatar asked Mar 06 '10 19:03

higherDefender


People also ask

Is there a swap method in Java?

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.

How do you swap items in Java?

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.

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.


2 Answers

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) 
like image 107
dansalmo Avatar answered Oct 08 '22 00:10

dansalmo


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.

like image 35
sepp2k Avatar answered Oct 08 '22 00:10

sepp2k